Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

Porgrammable Connection

$
0
0

I am trying to setup my connection to entity via code as I have to give the user the option to change database with same schema. Now it seems to build the connection string fine but it throws the following error

        public string SetupConnections()
        {



            //Specify the provider name, server and database.
string providerName = "System.Data.EntityClient";
            string serverName = "sourcenet";
            string databaseName = "COASTALCAROLINAPODIATRY";

            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
                new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity   = false;
            sqlBuilder.UserID = "";
            sqlBuilder.Password = "";

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
            Console.WriteLine(entityBuilder.ToString());

            using (EntityConnection conn =
                new EntityConnection(entityBuilder.ToString()))
            {
                conn.Open();
                Console.WriteLine("Just testing the connection.");
                conn.Close();
            }
            return sqlBuilder.ToString();
        }
        public void AddToPatient(Patient newPatient)
        {
            using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
            {
                myContext.Patients.Add(newPatient);
                try
                {
                    myContext.SaveChanges();
                }

                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                        }
                    }

                }
            }
        }

But i am getting the following error 

An unhandled exception of type 'System.ArgumentException' occurred in EntityFramework.dll

Additional information: The ADO.NET provider with invariant name 'System.Data.EntityClient' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details.

Even thoguh my app config uses entity.frame

  <add name="SMBASchedulerEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=sourcenet;initial catalog=COASTALCAROLINAPODIATRY;User ID=scheduler;Password=removed for security;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

 


Database Connection does not work when build up using sqlbuilder for entity

$
0
0

When I try to build up my connection string for entity frame work I cant see the data when I pass connection string to the base constructer object as directed

Here you will see I have a constructer in my entites object.

     // private  SystemDa _systemDB = new SystemDa();
          private string connectionstring;
        public string Connectionstring
    {
            get { return connectionstring; }
            set { connectionstring = SetupConnections(); } //instead of 'value', "Hip Hop" is written because
                                    //'value' in 'g1' was set to "Hip Hop" by previously
                                    //writing 'g1.Name = "Hip Hop"'
        }

Which I pass to my entite using below

 public partial class SMBASchedulerEntities : DbContext
    {
        public SMBASchedulerEntities()
            : base("name=SMBASchedulerEntities")
        {
        }

        public SMBASchedulerEntities( string connectionString)
        : base(connectionString)
    {
            Database.Connection.ConnectionString = connectionString;
        }

If I use the standard constructor everything works and data loads when I use the connection string constructor no data 

This is what is generated by the below method

"Data Source=sourcenet;Initial Catalog=COASTALCAROLINAPODIATRY;Integrated Security=True;User ID=scheduler;Password=\"pass""
   public string SetupConnections()
        {

            SqlConnectionStringBuilder sqlBuilder =
                    new SqlConnectionStringBuilder();

            try
            {
                //Specify the provider name, server and database.
                string providerName = "System.Data.SqlClient";
                string serverName = "sourcenet";
                string databaseName = "COASTALCAROLINAPODIATRY";

                // Initialize the connection string builder for the
                // underlying provider.

                // Set the properties for the data source.
                sqlBuilder.DataSource = serverName;
                sqlBuilder.InitialCatalog = databaseName;
                sqlBuilder.IntegratedSecurity = true;
               sqlBuilder.UserID = "scheduler";
              sqlBuilder.Password = "pass";

                // Build the SqlConnection connection string.
                string providerString = sqlBuilder.ToString();

                // Initialize the EntityConnectionStringBuilder.
                EntityConnectionStringBuilder entityBuilder =
                    new EntityConnectionStringBuilder();

                //Set the provider name.
                entityBuilder.Provider = providerName;

                // Set the provider-specific connection string.
                entityBuilder.ProviderConnectionString = providerString;

                // Set the Metadata location.
                entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
                Console.WriteLine(entityBuilder.ToString());

                using (EntityConnection conn =
                    new EntityConnection(entityBuilder.ToString()))
                {
                    conn.Open();
                    Console.WriteLine("Just testing the connection.");
                    conn.Close();
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }

            }

            return sqlBuilder.ToString();

How to fetch master detail data using EF and LINQ

$
0
0

suppose i have a order and order detail entity. i want to fetch specific order data and its related order detail by EF.

can i use this LINQ query

IEnumerable<Order> order= _ctx.order
            .Include(x => x.orderdetails)
            .Where(x => x.OrderID== _OrderID).ToList();

does the above code works fine? also tell me how to achieve the same with join also?

also tell me if i need to show specific customer data and customer order and order details then how i need to compose my EF query? help me with code. thanks

When people use join using EF

$
0
0

with the help of include function we can fetch related data. so tell me a scenario when i need to use join using EF because include does the join when fetch data.

please tell me a situation when people will not use include rather use or compose join using EF?

IEnumerable<Order> order= _ctx.order.Include(x => x.orderdetails).Where(x => x.OrderID==_OrderID).ToList();

Entity will add record to database but it will not update it.

$
0
0

Context is not saving to the database no matter what i do it will insert a new record fine but not save

    private void btnOk_Click(object sender, EventArgs e)

	{



		  SourceContext SourceDal = new SourceContext();



		Appointment _appointment = new Appointment();

		int errorCount = 0;



		Patient _patient = new Patient();

		_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);

		_patient.SSN = txtSSN.Text;



		_patient.FirstName = txtPatientFirstName.Text;

		_patient.LastName = txtPatientLastName.Text;

		_patient.Middle = txtPatientMiddle.Text;

		_patient.AddressOne = txtPatientAddressOne.Text;

		_patient.City = txtPatientCity.Text;

		_patient.State = txtPatientState.Text;

		_patient.ZipCode = txtPatientZip.Text;





		_patient.HomePhone = txtPatientHomePhone.Text;

		_patient.WorkPhone = txtPatientWorkPhone.Text;

		_patient.CellPhone = txtPatientCellPhone.Text;



		if (rBtnHomePhone.Checked == true)

			_patient.ApptPhone = txtPatientHomePhone.Text;

		if (rBtnHomePhone.Checked == true)

			_patient.ApptPhone = txtPatientHomePhone.Text;

		if (rBtnWorkPhone.Checked == true)

			_patient.ApptPhone = txtPatientWorkPhone.Text;





		_patient.BirthDate = dtBirthDate.DateTime;

		_patient.emailAddress = txtPatientEmail.Text;

		_patient.Race = (int)dpRace.SelectedValue;

		_patient.Ethnicity = (int)dpEthnicity.SelectedValue;

		_patient.Language = (int)dpLanguages.SelectedValue;



		_patient.AlertNote = txtPatientNotes.Text;





		if (dpGender.Text == "")

		{

			dpGender.Focus();

			errorCount = 1;

			lblGenderRequired.Text = "* Gender is required.";



		}

		else

		{

			errorCount = 0;

			lblGenderRequired.Visible = false;

		}

		_patient.Gender = dpGender.Text.Substring(0, 1);









		_patient.PatientID = txtPatientId.Text;

		txtPatientFirstName.Text = _patient.FirstName;

		txtPatientLastName.Text = _patient.LastName;

		// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.

			SourceDal.AddToPatient(_patient);

    }

Add to paitent has the following

    public void AddToPatient(Patient newPatient)

        {

            using (var myContext = new SMBASchedulerEntities(this.Connectionstring))

            {

                myContext.Patients.Add(newPatient);



                if (newPatient.ID == 0)

                {

                    myContext.Entry(newPatient).State = EntityState.Added;

                }

                else

                {

                    myContext.Entry(newPatient).State = EntityState.Modified;

                }

                try

                {

                    myContext.SaveChanges();

                }



                catch (DbEntityValidationException ex)

                {

                    foreach (var entityValidationErrors in ex.EntityValidationErrors)

                    {

                        foreach (var validationError in entityValidationErrors.ValidationErrors)

                        {

                            Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);

                        }

                    }



                }

            }

        }

It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.

How do I insert bulk data with Entity framework Core;

$
0
0

Hi,

In a part of my project I should insert a lots of users in the database (sql server) with Entity framework core and reading data from an Excel file .

How do I insert bulk data ?

Thanks in advance.

update json format in table

$
0
0

Hi,

I have table:

tbl_Posts: ID, Post, Replies

In column Replies I have format:

{  "data": [{"ID": "1"
,    "AuthorUserID": "1236645","Replies": "8e5s22t","DeletePost": "no"

  }]
}

I want update DeletePost like that:

 var display = from t1 in db.tbl_Posts where t1.ID == 1 && t1.Replies==this need to get from Linq ID select t1;

then I need to use

display.FirstOrDefault.DeletePost="yes"
db.SubmitChanges()

So, First I need to find t1.ID==1 then, I need to find from coumn Replies ID from linq and update linq format: DeletePost="yes" or "No".

Please help.

How to create data access layer when working with EF

$
0
0

i read article on repository pattern. people create a extra abstract layer on top of EF to do CRUD operation.

just read https://www.infoworld.com/article/3117713/application-development/design-patterns-that-i-often-avoid-repository-pattern.html

guide me how could i create and structure my classes to do the crud operation.

is it really good to create a repository or generic repository which internally use EF to do the crud?

repository is standard one for real life production environment?

should i create business class from where i can use EF to play crud.......would be good choice for production environment?

please guide me how could i develop Data access layer to do the crud operation using EF.

thanks


EF LINQ: How to fetch data from few specific column

$
0
0

List<string> cities = new List<string>() {"London","Vancouver", "San Francisco"};var cutomers = from cin Customers where cities.Contains(c.City)select c;

how to specify column names

IEnumerable<Order> order= _ctx.order.Include(x => x.orderdetails).Where(x => x.OrderID==_OrderID).ToList();

suppose i want extract few specific column data from order and orderdetail table then how to achieve it.

odp.net Null date issue with Oracle

$
0
0

We just updated to odp.net 4 and we have a date field on a form that when we try to pass this to our oracle procedure in the backend it get's a Not a Valid Month.

Looking at the code it in the Attachparameter code below it checks for null but this doesn't seem to work. We tried to put in a check and reset the value to DBNull.Value but we still get that not a valid Month error. Any help would be appreciated. 

We tried setting p.Value = OracleString.DBnull  but that gave an oracle error.  We got it to find the null with p.value=(object)System.Dbnull.value and directly set the p.value=Dbnull.value but that still gave the Oracle month error. So were not sure how to fix this issue.(code below)

 dpDataParamArr = New ArrayList

dpDataParamArr.Add(New DataParameter(STP_Constants.SAVE_ORG_REQ, STP_Constants.P_APPROVAL_DT, "DATETIME", Now, ParameterDirection.Input, 10, Req_Contants.COL_APPROVAL_DT, DataRowVersion.Current))   <--field iwth nulll

  UpdateDatasetTable(dsRequestSchema, dsRequestSchema.Tables(RequestSchema.ELEMENTS).TableName, Nothing, arrParameters, STP_Constants.PKG_M

                                 STP_Constants.SAVE, STP_Constants.SAVE, "DELETE", idbConn, idbtrax)  <--procedure to call dll that interfaces with oracle

helper.UpdateDataset(IdbInsertCommand, IdbDeleteCommand, IdbUpdateCommand, dsSrcDataset, strTableName)

DLL code below:

public void UpdateDataset(IDbCommand insertCommand, IDbCommand deleteCommand, IDbCommand updateCommand, 

DataSet dataSet, string tableName, RowUpdatingHandler rowUpdatingHandler, RowUpdatedHandler rowUpdatedHandler) 

{

int rowsAffected = 0;

 

if( tableName == null || tableName.Length == 0 ) throw new ArgumentNullException( "tableName" ); 

 

// Create an IDbDataAdapter, and dispose of it after we are done

IDbDataAdapter dataAdapter = null;

try

{

bool mustCloseUpdateConnection = false;

bool mustCloseInsertConnection = false;

bool mustCloseDeleteConnection = false;

 

dataAdapter = GetDataAdapter();

                

// Set the data adapter commands

dataAdapter.UpdateCommand = SetCommand(updateCommand, out mustCloseUpdateConnection);

dataAdapter.InsertCommand = SetCommand(insertCommand, out mustCloseInsertConnection);

dataAdapter.DeleteCommand = SetCommand(deleteCommand, out mustCloseDeleteConnection);

 

AddUpdateEventHandlers(dataAdapter, rowUpdatingHandler, rowUpdatedHandler);

if( dataAdapter is DbDataAdapter ) 

{

// Update the DataSet changes in the data source

try

{

rowsAffected = ((DbDataAdapter)dataAdapter).Update(dataSet, tableName);

catch (Exception ex) 

{

// Don't just throw ex.  It changes the call stack.  But we want the ex around for debugging, so...

Debug.WriteLine(ex);

dataAdapter = null;

if (mustCloseUpdateConnection)

{

updateCommand.Connection.Close();

}

if (mustCloseInsertConnection)

{

insertCommand.Connection.Close();

}

if (mustCloseDeleteConnection)

{

deleteCommand.Connection.Close();

}

ExceptionManager.Publish(ex);

throw ex;

}

}

else

{

dataAdapter.TableMappings.Add(tableName, "Table"); 

// Update the DataSet changes in the data source

rowsAffected = dataAdapter.Update (dataSet); 

}

 

// Commit all the changes made to the DataSet

dataSet.Tables[tableName].AcceptChanges();

 

if (mustCloseUpdateConnection)

{

updateCommand.Connection.Close();

}

if (mustCloseInsertConnection)

{

insertCommand.Connection.Close();

}

if (mustCloseDeleteConnection)

{

deleteCommand.Connection.Close();

}

}catch (Exception e)

{

Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(e);

throw e; 

}

finally

{

if ( insertCommand != null )

{

insertCommand.Dispose();

//dataAdapter.InsertCommand.Dispose();

}

 

if ( updateCommand != null )

{

updateCommand.Dispose();

//dataAdapter.UpdateCommand.Dispose();

}

 

if ( deleteCommand != null )

{

deleteCommand.Dispose();

//dataAdapter.DeleteCommand.Dispose();

}

IDisposable id = dataAdapter as IDisposable;

if( id != null ) id.Dispose();

}

}

protected virtual IDbCommand SetCommand(IDbCommand command, out bool mustCloseConnection )

{

mustCloseConnection = false;

if (command != null)

{

IDataParameter[] commandParameters = new IDataParameter[ command.Parameters.Count ];

command.Parameters.CopyTo( commandParameters, 0 );

command.Parameters.Clear();

this.PrepareCommand( command, command.Connection, null, command.CommandType, command.CommandText, commandParameters, out mustCloseConnection );

CleanParameterSyntax(command);

}

return command;

}

 

protected virtual void PrepareCommand(IDbCommand command, IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDataParameter[] commandParameters, out bool mustCloseConnection )

{

if( command == null ) throw new ArgumentNullException( "command" );

if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" );

 

// If the provided connection is not open, we will open it

if (connection.State != ConnectionState.Open)

{

mustCloseConnection = true;

connection.Open();

}

else

{

mustCloseConnection = false;

}

 

// Associate the connection with the command

command.Connection = connection;

 

// Set the command text (stored procedure name or SQL statement)

command.CommandText = commandText;

 

// If we were provided a transaction, assign it

if (transaction != null)

{

if( transaction.Connection == null ) throw new ArgumentException( "The transaction was rolled back or commited, please provide an open transaction.", "transaction" );

command.Transaction = transaction;

}

 

// Set the command type

command.CommandType = commandType;

 

// Attach the command parameters if they are provided

if (commandParameters != null)

{

AttachParameters(command, commandParameters);

}

return;

}    

protected virtual void AttachParameters(IDbCommand command, IDataParameter[] commandParameters)

{

if( command == null ) throw new ArgumentNullException( "command" );

if( commandParameters != null )

{

foreach (IDataParameter p in commandParameters)

{

if( p != null )

{

// Check for derived output value with no value assigned

if ( ( p.Direction == ParameterDirection.InputOutput || 

p.Direction == ParameterDirection.Input ) && 

(p.Value == null))  <--doesn't find

{

p.Value = DBNull.Value;

}

if (p.DbType == DbType.Binary) 

{

// special handling for BLOBs

command.Parameters.Add(GetBlobParameter(command.Connection, p));

}

else if (p.DbType == DbType.Object)//special handle for large strings

{

command.Parameters.Add(GetClobParameter(command.Connection, p));

}

else

{

command.Parameters.Add(p);

}

}

}

}

}

Entity wont save changes no mattter what but adds records fine

$
0
0

   public Patient getPatientByPatientNewId(int newId)
        {

            Patient patient = new Patient();
            if (newId == -1)
            {
                patient = new Patient();
            }
            else
            {
                using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
                {
                    patient = myContext.Patients
                   .Where(w => w.ID == newId).FirstOrDefault();
                }
            }
            return patient;

        }
     

Entity framework will not update an entity no matter what I do it will add a record fine but not update existing one

     private void btnSave_Click(object sender, EventArgs e)
        {
            Patient _newpatient = new Patient();
            if(txtID.Text !="")
            _newPatient = SourceDal.getPatientByPatientNewId(Convert.ToInt32(txtID.Text));


            _newPatient.emailAddress = "test UPDATE";
            _newPatient.Gender = "M";
            SourceDal.SaveChanges();

        }

Here is my funciton that retrieves the single record so that i can make a change to iit , when i look futher at my save changes method it says that the patient table remains unchanged even though it has changed via the code above

Add Column with Delta values

$
0
0

Hi ,

I need to add one more column in datatable using linq for calculating delta between values

AOutputCalculation
25
91625-9=16
78699-78=69
552378-55=23
332255-33=22
885533-88=55

Thanks for your help!

How can I run the query with Linq?

$
0
0

Hi 

I have the query:

select * from Unidad u left join ParametroValor p1 on u.IdTipoUnidad = p1.Id
left join ParametroValor p2 on u.IdEstado = p2.Id
where u.Placa = '' and p1.test='333'

How can I run the query with Linq?

 

Using [Key] attribute for primary key in code-first w/ Entity-Framework

$
0
0

If I designate a field with the [Key] attribute in code-first design, can I name the field whatever I want, or does Entity-Framework expect the Primary key field to be called "Id"?

What I'm looking to create is a table like this (for a photo gallery):

public class Pictures {
  [Key]
[Required] public int PictureId;

[Required]
[Display(Name = "File URL")]
public string FileURL;


[Display(Name = "Caption")]
public string CaptionText;

// .. additional fields...
}

(I've had issues in the past with database-first and E-F that sometimes, even though a field (such as "PictureId") was defined as a primary key in the database, when I went to add new records with E-F, it would give errors saying there was no primary key defined, despite the field "PictureId" being specified as an auto-increment primary key in the database definition/SQL when the table was created).

EF default internationalization

$
0
0

Hi guys, sorry for boddering but after few hours of serching the internet for a loggical solution I've finnaly surrenderd and thought that you could help me.

The problem is that when I run my app locally filds are translated (the default asp .net EF model translation), as shown below on the image are corrent depending on my culture info pl-PL. But after pasting my project on production serwer languge of the text is always in English... shown below. Other texts that are not auto but using resuorces files work fine. When I change the culture info the language changes - only the default translation are not correct...

Oh and meybe thats important too: locally when I change to EN texts are also correct (in English). I've copied all files that are in my bin folder to the production server.

Image link


Having problems with FirstofDefault returning wrong values.

$
0
0

I have what looks to me to be a straitforward query:

VirtualWallet WalletItem = context.VirtualWallets.FirstOrDefault(w => w.TokenID == theItem.TokenId);

The table in the database has two rows.  the value of the TokenID field (which is a type of char(36)) in those two rows is 'blah' and 'blah2' respectively. 

If the value of theItem.TokenId = 'Blah', the EF query above will return the row with the TokenID of 'blah' - padded with spaces.  This is not what I'm expecting.  I need it to be a case-sensitive search.

But now if the value of theItem.TokenId is something far removed like 'Fred', then WalletItem will be null as expected.  

This is with a SqlServer database on the back end.  

Any ideas what I'm doing wrong?  Do I have something configured wrong somewhere else in the app?

ComponentModel data annotations: explicitly defining database table name separate from class name in code

$
0
0

So I'm working on a photo gallery as a project, and have a class named Category (used to categorize pictures), which holds basic information about a category (basically a unique ID that can be referenced in other tables, and a name field):

public class Category
{
  [Key]
  [Required]
  public int Id;

  [Required]
  [Display(Name = "Category Name")]
  public string Name;
}

I'm using E-F code first in this project, and wanted to know if there is a way that I can tell E-F / SQL server to use the table name "Categories" instead of "Category" which it would pick up by default based on the class name when the E-F relationship data model is added/built.  Is there a annotation I can use to specify the name of the table that E-F should use rather than the class name?  I want to specify this, so that when I create instances of this class (Category) it's easy to read, and doesn't look like:

public cat = new Categories();
// I don't want this

public cat = new Category();
// I want this

// But I want SQL Server / E-F to call the entity "Categories" in the database

Ideas?

reduce (or eliminiate) possibliity of 2+ users updating same record at the same time

$
0
0

Does ADO.NET E-F prevent two users from updating the same record in a table at the same time (ie. saving the record at the same time, thus clobbering eachother's changes)?

If not, how can I reduce this or eliminate this possibility with E-F?

Linq like to_char statement

$
0
0

Hi All,

I have the following SQL condition that I need to write with LINQ on my Visual Studio:

and bat_id like to_char(start_dt,'yyyyMMdd')||'%'

Where COLUMN2 is a date type column. 

Could anybody please help me?

LINQ is no longer being updated / being phased out??

$
0
0

I saw in a Lynda training video a while back that the instructor had mentioned (and this was maybe 3 years ago) that Microsoft was not really going to continue to "support" (or improve/update I guess) LINQ as they want people to sort of move to E-F instead?

Either way, is it true that LINQ is starting to be phased out in favor of newer technologies (as I guess LINQ has been around for the past 5-10 years ?)  I never really bought onto the LINQ syntax, as I'm more used to actual SQL syntax so it was confusing for me to pick up, even though it's just the order of the wording/syntax that's different, but reads almost the same as regular SQL.

Viewing all 1698 articles
Browse latest View live