EntityFramework6 with WPF update - c#

I have a EF6 data context that I'm manually binding to a form with the method below.
private void GetJob(int i)
{
var context = new APIntegrationEntities();
var jb = context.Jobs.Find(i);
//tJobName.AppendText(jb.JobName.ToString());
tId.Text = jb.Id.ToString();
tJobName.Text = jb.JobName;
tSourceQuery.Text = jb.SourceQuery;
tAPI.Text = jb.API;
tConnectionString.Text = jb.ConnectionString;
tSheetName.Text = jb.SheetName;
tVersion.Text = jb.VersionName;
}
I'm trying to update with the following :
private void bSave_Click(object sender, RoutedEventArgs e)
{
var context = new APIntegrationEntities();
var jb = context.Jobs.Find(Int32.Parse(tId.Text));
jb.JobName = tJobName.Text;
jb.SheetName = tSheetName.Text;
jb.SourceQuery = tSourceQuery.Text;
jb.ConnectionString = tConnectionString.Text;
jb.VersionName = tVersion.Text;
jb.Id = Int32.Parse(tId.Text);
jb.API = null;
context.SaveChanges();
}
But I get an exception :
System.Data.Entity.Validation.DbEntityValidationException was unhandled
HResult=-2146232032
Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source=EntityFramework
Am I using the EF correctly? Is there a better way to bind the context to the form and process the updates?

You are using EF technically correctly but not very good from design point of view.
Exception that you have got means that you are trying to pass in job entity some illegal from database point of view data (for example DateTime that doesn't fit in datetime DB type, null in non-null column, string with length that exceeds maxlength etc.).
So you need to see exception details and figure out what particular property causes a problem and correct the the data you are passing in it.

Related

recover "DbContext" lost out after a method

I need your help.
I begin to ASP.net and I fail to retrieve a "dbcontext" to display my request in a "datagrid". Here is my code:
public IQueryable<DiagTab> Clooper(string m_ValEnvoi)
{
string Ladatatable = m_ValEnvoi;
using (var db = new DiagEntities())
{
var secki = db.DiagTabs.Where(Ladatatable); // Ladatatabase = Dynamic LinQ
return secki;
}
I call this way (no error)
TheLoop pilou = new TheLoop();
pilou.Clooper(Valtest);
var olami = pilou.Clooper(Valtest);
but if i try this:
var selection_click = olami;
GridView1.DataSource = selection_click.ToList();
GridView1.DataBind();
the code is interrupted and displays "Could not complete the operation because the DbContext has been deleted".
Is it possible to get the paste has Dbcontext for this request?
thanks for your help
You should call ToList() inside the method, before disposing the DbContext.
Don't use using which dispose the DiagEntities and instead of it, if you want to use it in several methods just declare a property for your DiagEntities in the class constructor.
public IQueryable<DiagTab> Clooper(string m_ValEnvoi)
{
string Ladatatable = m_ValEnvoi;
var secki = db.DiagTabs.Where(Ladatatable); // Ladatatabase = Dynamic LinQ
return secki;
}

Unable to save data to Entity Model Database using saveChanges() method

I am trying to save data to my database. What I want is that when the button is pressed, data is saved to the database permanently. I've done tests where code is saved while the application is running. The saved data is viewable. But when I terminate the application, the data is not present when I view the data for that table in visual studio. I've provided the code that I am using for testing.
private void btn_otrFun_Click(object sender, EventArgs e)
{
tblCheese cheese = new tblCheese();
string cheesename = "TestCheese";
cheese.CheeseName = cheesename;
cheese.CheeseGroup = 1;
cheeseEntity.tblCheese.AddObject(cheese);
cheeseEntity.SaveChanges();
}
Here is where I am getting the context form. It is instantiated at the beginnning of the form.
private CheeseWorld_DatabaseEntities cheeseEntity = new CheeseWorld_DatabaseEntities(); //instanciate new database entities
And further I am using this snippet to retrieve data from the the database to dynamically created buttons.
var cheeselist = cheeseEntity.ExecuteStoreQuery<tblCheese>("Select * FROM tblCheese WHERE cheeseGroup = 1", null).ToList();
Hope these further details help. If more are required, let me know.
You've departed from the normal pattern we usually use for this... maybe try putting it back to something like this... (I don't see where you are getting the context)
using (var context = new cheeseEntity()) {
tblCheese cheese = new tblCheese();
cheese.CheeseName = "TestCheese";
cheese.CheeseGroup = 1;
context.tblCheese.Add(cheese);
context.SaveChanges();
}
This is covered in the documentation: http://msdn.microsoft.com/en-us/data/jj593489
(Pay attention to the bottom where it shows how to trace the generated SQL)
NOTE: I am using Add instead of AddObject.

Error when trying to loop through entities from an Azure Table

i keep getting this error, "The current value 'String.Empty' type is not compatible with the expected 'System.Boolean' type", when i try to loop through a bunch of entities from an Azure table, i am only new to using Azure so this could be something very easy, the error that i am getting.
my code :
private void registerButton_Click(object sender, RoutedEventArgs e)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Get the data service context
TableServiceContext serviceContext = tableClient.GetDataServiceContext();
// Create a new customer entity
user = new UserDetailsEntity();
//Setting the fields of the new userEntity
user.username = usernameText.Text;
user.password = passwordText.Text;
user.subscriptionID = subText.Text;
user.subscriptionName = subscriptionNameText.Text;
user.thumbprint = thumbprintText.Text;
user.email = emailText.Text;
user.phoneNumber = "3530" + numberText.Text;
int rowCount = 1;
CloudTableQuery<UserDetailsEntity> Query = (from en in serviceContext.CreateQuery<UserDetailsEntity>("userdetails")
select en).AsTableServiceQuery<UserDetailsEntity>();
//error occurs in the next line
foreach (UserDetailsEntity ent in Query)
{
rowCount++;
}
user.RowKey = rowCount.ToString();
// Add the new customer to the people table
serviceContext.AddObject("userdetails", user);
// Submit the operation to the table service
serviceContext.SaveChangesWithRetries();
//Set the variables so they can be retrieved when the next screen loads
Application.Current.Properties["username"] = usernameText.Text;
Application.Current.Properties["password"] = passwordText.Text;
Window1 userHome = new Window1();
this.Close(); //to close Password window
userHome.Show(); //to show Main form
}
Without more code, I cannot tell you exactly where the problem is, however the exception is fairly explanatory. You are trying to set a boolean property to a value of a string.
If the error is occurring in your foreach as you noted in the code comment, then I would check how your UserDetailsEntity object is set up. There is probably a property that is set up as a boolean, yet your data is coming back as a String.Empty. The reason you are getting this in your foreach is because your LINQ query is of type IQueryable, so it will not actually execute and fill your objects until you actually access the data (by your foreach)*. So, you could put breakpoints in your UserDetailsEntity properties to see which one it is if this is not blatent from looking at the code.
*Keep in mind that this is the N+1 problem, where you are making a call to the database on each iteration of your loop. You can resolve this by calling .ToList() to eager load all of your data at once into your query...if this is a problem for you, that is.

The EntityKey property can only be set when the current value of the property is null

i'm trying to execute an EF update in the following manner but continue to receive this error:
The EntityKey property can only be set when the current value of the property is null.
using (hydraEntities db = new hydraEntities())
{
YouUser = db.youusers.Include("address").Include("entity").Include("youusercontacts.contact").Include("youuserlogins").Include("youusernotes.note").Include("youusernotes.youuser.entity").Where( yu => yu.YOUUserId.Equals(YOUUserId)).First();
}
YouUser.entity.FirstName = txtFirstName.Text;
YouUser.entity.LastName = txtLastName.Text;
YouUser.address.AddressLine1 = txtAddressLine1.Text;
YouUser.address.AddressLine2 = txtAddressLine2.Text;
YouUser.address.City = txtCity.Text;
YouUser.address.State = ddlState.SelectedValue;
YouUser.address.Zipcode = txtZipcode.Text;
using (hydraEntities db = new hydraEntities())
{
db.youusers.AddObject(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
Would greatly appreciate any insight on how I can fix this and execute the statement above.
Don't use AddObject in this scenario. It is for inserting a new entity but you are updating existing one. Use Attach instead:
using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
In my scenario I was adding objects several times at once through different threads. I had to lock the Model Container object when doing this, to make sure only one object would be processed at once.

EF4 error:The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

hi I have a question I'am using for my web site wscf in vs2010 that use de model MVP(model,view,presenter) and for my model layer (data acces layer) iam using EF
that seguimiento's tables is an intermediate table between be cliente and gventa tables
so I have my Insert in seguimiento's table with L2E in my (DAL LAYER)like this
public void InsertarSeguimiento(Seguimiento Seg)
{
using (var cont = new CelumarketingEntities())
{
cont.AddToSeguimiento(Seg);
cont.SaveChanges();
}
}
and in my presentation'S layer, I capture for my web form, from textbox the field for seguimiento And I get these error when I try to put the object cliente to (seguimiento) objProxy.ClienteReference.Value
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
and I don't understand why since gventa object have no that error
protected void BtnInsertar_Click(object sender, EventArgs e)
{
string nombreGVentas = TbxVendedor.Text;
char[] delimit = new char[] { ' ' };
string[] arreglo = nombreGVentas.Split(delimit);
GVenta IdGVentas = _presenter.getventas(arreglo[0], arreglo[1]);
string nombrecliente = TbxCliente.Text;
Project.CAD.Cliente idCliente = _presenter.getCliente(nombrecliente);
string hora = DdlHora.SelectedValue;
string minutos = DdlMinutos.SelectedValue;
string HorMin = hora + ":" + minutos;
Project.CAD.Seguimiento objProxy = new Project.CAD.Seguimiento();
objProxy.GVentaReference.Value = IdGVentas;
objProxy.ClienteReference.Value = idCliente; *// here i get the errors*
objProxy.Descripccion = TbxDescripccion.Text;
objProxy.Fecha = Calendar1.SelectedDate;
objProxy.Hora = HorMin;
_presenter.insertarseg(objProxy);
}
Problem is that your idCliente is already attached to the context here:
Project.CAD.Cliente idCliente = _presenter.getCliente(nombrecliente);
So, when you try to assign it to the other object that's also in some other context (the line where you get the error), the EF throws error since it don't know what object to put in what context (it can belong to only one context).
What you need to do is to detach idCliente from it's context before returning in _presenter.getCliente() method.

Categories

Resources