i've got some trouble with EF (6.0.0)
here is the code
var Answer = new TicketAnswer();
Answer.Answer = "hello";
Answer.TicketId = 20;
Answer.ConfirmDate = DateTime.Now;
db.TicketAnswer.Add(Answer);
db.SaveChanges();
AnswerId = Answer.ID;
db.TicketAnswer.Where(x=> x.ID == AnswerId).FirstOrDefault();
after that , when im trying to get the db.TicketAnswer with the same Id of the Answer (which is new created) EF returning with TicketAnswer class (not a proxy) and i cant access to Ticket class over that (Ticket Property is null even TicketId is not null and there is Ticket on the db which Id = 20 , there is not problem with relations) , but when i change my query to :
var a = db.TicketAnswer.Where(x => x.ID == 225).FirstOrDefault();
EF returning back with System.Data.Entity.DynamicProxies_ASDGAFD... and i can access to Ticket class.
All i want is , reach Ticket class over TicketAnswer class , What should i do ?
Your navigation property has not yet loaded for the newly added entity in that context. To load it you must:
var ticketAnswer = db.TicketAnswer.Include(ta => ta.Ticket).Where(x=> x.ID == AnswerId).FirstOrDefault();
or better:
var ticketAnswer = db.TicketAnswer.Include(ta => ta.Ticket).Single(ta=> ta.Id == answerId);
One may ask "Then why the other entity (with Id == 225) is loaded without using this .Inlcude thing?"
The answer is: That entity was added surely by and other run session, using an other db context instance. So that entity in not in the cache of the current db context instance. When asking for it, EF will load it, and navigation properties are available without explicit Include. However the freshly added entity is in the cache, with no navigation properties. Simple asking for it using where will give you back the very same instance you've added. Note: not just very same entity: the very same instance.
To navigate multiple hops in your entity graph you can use:
.Include("Ticket.User") // In case if the Ticket entity has a navigation property called 'User'
Related
I have these two tables:
public class FiscalYear
{
... other fields
public int FiscalYears_Id { get; set; }
}
public class SkipHeader
{
... other fields
public int FiscalYears_Id { get; set; }
public virtual FiscalYear FiscalYear { get; set; }
}
Attempting to create a new SkipHeader like so:
var skipHeader = new SkipHeader()
{
... other fields get assigned to
FiscalYear = Session.FiscalYear,
}
Will cause the database to create a new FiscalYear record instead of using the Session.FiscalYear which is simply a static property that gets assigned to at program start. However, if I assign the FiscalYears_Id instead:
var skipHeader = new SkipHeader()
{
... other fields get assigned to
FiscalYears_Id = Session.FiscalYear.FiscalYears_Id,
}
The program uses the existing record as expected.
This bug eluded me and my colleague for months! Now that I found a solution, I would like to know WHY this is the case?
This bug eluded me and my colleague for months! Now that I found a
solution, I would like to know WHY this is the case?
This occurs because the DbContext doesn't know about your FiscalYear object instance, such as whether it represents a new record or an existing one.
Take the following example:
var fiscalYear = new FiscalYear { Id = 4, Name = "2019/20" };
var skipHeader = new SkipHeader { FiscalYear = fiscalYear };
context.SkipHeaders.Add(skipHeader);
context.SaveChanges();
fiscalYear in this instance is an object instance that has been given an ID and Name. When we associate it to a new SkipHeader and add the SkipHeader to the DbContext, EF will see this fiscalYear. Since it isn't an object tracked by the context, it treats it as a new entity like the SkipHeader.
Depending on how your entities are configured for dealing with the PK will determine what happens.
If your PK (Id) is set up as an Identity column (DB will populate) then the FiscalYear will be inserted and assigned the next available Id value. After the SaveChanges() call, fiscalYear.Id would be "6" or "22" or whatever the next new ID assigned to it would be. (Not "4")
If your PK is not an Identity column (App will populate) and a FiscalYear row already exists in the DB for ID 4, then EF will throw a duplicate key Exception on SaveChanges().
Where people get confused is that they assume that since the FiscalYear was at one point (Say during a web request) loaded from a DbContext, it is still somehow acting as a tracked entity when passed into another method outside of the scope of that DbContext. (During another update web request) It's not. When a web request for instance accepts a FinancialYear as a parameter from the client, it is deserializing a FinancialYear. As far as EF is concerned, that is absolutely no different than the new FinancialYear { } example above. The DbContext is not aware of that entity.
Take the following example:
FiscalYear fiscalYear = null;
using (var context = new AppDbContext())
{
fiscalYear = context.FiscalYears.Single(x => x.Id == 4);
}
using (var context = new AppDbContext())
{
var skipHeader = new SkipHeader { FiscalYear = fiscalYear };
context.SkipHeaders.Add(skipHeader);
context.SaveChanges();
}
This provides a basic outline of a Fiscal Year that was loaded by one instance of a DbContext, but then referenced by another instance of a DbContext. When SaveChanges is called, you will get a behaviour like you are getting now. This is what essentially happens in web requests, as when an entity is returned, the entity definition is merely a contract and the Entity is serialized to send to the client. When it comes back into another request, a new untracked object is deserialized.
As a general rule, Entities should not be passed outside the scope of the DbContext they were read from. EF does support this via detaching and re-attaching entities, but this is honestly more trouble than it is typically worth because you cannot 100% rely on just attaching an entity using DbContext.Attach() as often there can be conditional cases where another entity instance is already being tracked by a context and the Attach will fail. In these cases you'd need to replace references with the already tracked entity. (Messy conditional logic to catch possible scenarios) References are everything when dealing with EF. Two different object references with the same key & values are treated as separate and different objects by EF. Rather than passing references around, it's usually a lot simpler, and better to pass just the FK. This has the benefit of being a smaller payload for web requests.
One option you've found out is to update via the FK:
var skipHeader = new SkipHeader()
{
... other fields get assigned to
FiscalYears_Id = Session.FiscalYear.FiscalYears_Id,
}
This works, however when you have entities that are exposing both FK (FiscalYears_Id) and navigation property (FiscalYear) you can potentially find mismatch scenarios when updating records. This is something to be careful with as an application evolves.
For instance, take an example where you are editing an existing SkipHeader with a FiscalYears_Id of "4". This will have an associated FiscalYear reference available with a PK of "4".
Take the following code:
var skipHeader = context.SkipHeaders.Include(x => x.FiscalYear).Single(x => x.Id == skipHeaderId);
skipHeader.FiscalYears_Id = newFiscalYearId; // update FK from "4" to "6"
var fiscalYearId = skipHeader.FiscalYear.Id; // still returns "6"
context.SaveChanges();
We set the FK value on the skip header, however that does not update the reference for FiscalYear until after we call SaveChanges. This can be an important detail when dealing with FKs alongside navigation properties. Now normally we wouldn't bother going to the Navigation Property to get the ID again, but any code we call that is expecting the new FiscalYear reference to be updated will have a different behavior depending on whether SaveChanges had been called before or after the code in question. If before, all FiscalYear details will be for the old fiscal year even though we changed the FK reference.
This can also lead to odd Lazy Loading errors as well such as:
var skipHeader = context.SkipHeaders.Single(x => x.Id == skipHeaderId);
skipHeader.FiscalYears_Id = newFiscalYearId; // update FK from "4" to "6"
var fiscalYearId = skipHeader.FiscalYear.Id; // NullReferenceException!
context.SaveChanges();
Normally, provided you have lazy loading enabled loading a SkipHeader without eager loading the FiscalYear (.Include(x => x.FiscalYear))and then querying a property from the FiscalYear would lazy load this relative. However, if you change the SkipHeader's FiscalYear_ID FK and then try to access a property off the FiscalYear before calling SaveChanges(), you will get a NullReferenceException on the FiscalYear. EF will NOT lazy load either the old or new FiscalYear entity. Bugs in behaviour like that commonly creep in as applications get developed and code starts calling common functions that assume they are dealing with complete entities.
The alternative to setting updated values for known rows by FK is to load the entity to associate, and associate it by reference:
using (var context = new AppDbContext())
{
var fiscalYear = context.FiscalYears.Single(x => x.Id == fiscalYearId);
var skipHeader = new SkipHeader()
{
... other fields get assigned to
FiscalYear = fiscalYear;
}
context.SaveChanges();
}
This example just uses a locally scoped DbContext. If your method has an injected context then use that instead. The context will return any cached, known instance of the Fiscal Year or retrieve it from the DB. If the FiscalYear ID is invalid then that operation will throw an exception specific to the Fiscal Year not being found due to the Single() call rather than a more vague FK violation on SaveChanges(). (Not an issue when there is only one FK relationship, but in entities that have dozens of relationships...)
The advantage of this approach is that the FiscalYear will be in the scope of the DbContext so any methods/code using it will have a valid reference. The entities can define the navigation properties without exposing the extra FK values,using .Map(x => x.MapKey()) [EF6] or Shadow Properties [EFCore] instead to avoid 2 sources of truth for FK values.
This hopefully will provide some insight into what EF is doing and why it resulted in the behaviour you've seen and/or any errors or buggy behaviour you might have also come across.
Assuming you have pretty standard setup with DbContext being scoped (per request) dependency - the reason is that the new instance of your DbContext does not track the Session.FiscalYear instance - so it creates new. Another way to solve this is using DbContext.Attach:
context.Attach(Session.FiscalYear);
var skipHeader = new SkipHeader()
{
... other fields get assigned to
FiscalYears_Id = Session.FiscalYear.FiscalYears_Id,
}
// save skipHeader
More about change tracker in EF.
in my code I'm loading an entity using its id , then update its content using AutoMapper and finally call Context.SaveChanges . but it's not working ! . but when I set properties manually it takes effect ! what is wrong ?
var entity = Context.MyEntities.Find(id);
entity = Mapper.Map<MyEntity>(viewModel);
Context.SaveChanges;
but this one works :
var entity = Context.MyEntities.Find(id);
entity.SomeProp = viewModel.SomeProp;
Context.SaveChanges;
then update its content using AutoMapper
This is not true - Mapper.Map<MyEntity>(viewModel) returns new instance of MyEntity class. It does not update properties of existing instance. You should attach that new instance to context:
var entity = Context.MyEntities.Find(id); // this line is useless
entity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(entity);
Context.SaveChanges;
Also retrieving entity from context does not makes sense when you are creating new one. You are reusing same variable for holding references to different objects, and that is confusing. What really happens could be described this way:
var entityFromDb = Context.MyEntities.Find(id);
var competelyNewEntity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(competelyNewEntity);
Context.SaveChanges;
In your second option you are updating properties of entity, which exists in context, you don't need to attach it.
BTW there is third option (and best) - use another mapping method, which updates destination entity instead:
var entity = Context.MyEntities.Find(id);
Mapper.Map(viewModel, entity); // use this method for mapping
Context.SaveChanges;
I have written test code as bellow:
Entities db = new Entities();
var place = new Place
{
Id = Guid.NewGuid(),
Name = "test",
Address = "address"
};
db.Places.Add(place);
var cachedPlace = db.Places.Where(x => x.Id == place.Id).FirstOrDefault(); \\ null
I expected dbset will return the added entity. But it gives me object only after changes were saved to the real DB.
If you want to access the unsaved query, then you use the Local property of the DbSet.
The reason it doesn't work the way you want is that it must also support autonumbered identities, and that will mean the ID is 0. If you insert multiple records, you would have multiple objects with the same 0 ID. EF won't know what the real ID is until after it's been saved.
I've a small problem with updating entities if the entity is changed outside the DbContext (is a detached entity). If I attach the modified entity, it's state is not modified.
My code looks like this:
var specificationToSave = GetSpecificationFromTmpStore(userSessionGuid);
using (var context = DataContextFactory.GetDataContext())
{
// this works for update, if I change the values inside the context while debugging
// but it breaks with new entities
context.Specifications.Attach(specificationToSave);
// this works for insert new entities, modified entities will be saved as new entities
context.Specifications.Add((specificationToSave);)
context.SaveChanges();
}
I know NHibernate and it's method SaveOrUpdate. NHibernate decides because of the values if it is updating or inserting the entities.
What is the best practice to do this with EF 4.x and with entities which are modified outside the DbContext?
How can I tell the EF that this entity is in modified state?
If you use the Attach approach on an entity which has already changed, you will also need to tell EF that the entity is modified, after attaching it.
context.Specifications.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
An alternative is to fetch (with tracking), then update the fields, and save:
var entity = context.Specifications.First(s => s.Id == 1234);
entity.Name = "Foo";
... other changes here
context.SaveChanges();
Another option is to make the changes to the entity after you have reattached it, e.g. as per here
context.Specifications.Attach(entity);
entity.Name = "Foo";
... other changes here
context.SaveChanges();
Edit
You can use generics with DbSet - either class, or method - as follows:
public void Update<TEntity>(TEntity entity)
{
DbContext.Set<TEntity>().Attach(entity);
DbContext.Entry(entity).State = EntityState.Modified;
DbContext.SaveChanges();
}
Edit : For updating of detached Parent / Child Graphs
For updating of simple / shallow parent-child relationships where efficiency and performance is not important, simply deleting all old children and reinserting the new ones is an easy (although ugly) solution.
However, for a more efficient scenario requires us to traverse the graph, detect changes, and then add newly inserted, update existing, ignore unchanged, and delete removed items from the Context.
Slauma shows a great example of this here.
You might want to look at using GraphDiff, which can do all this leg work for you!
For disconnected entities, I found this solution.
For finding changes on an existing entity:
var existing = context.Find<Item>(1);
if (existing != null)
{
context.Entry(existing).CurrentValues.SetValues(changed);
}
Its EntityState will be Modified afterwards but only where there are actual changes.
Full example I did in a unit/integration test:
await using var context1 = new MyContext(new DbContextOptionsBuilder().UseSqlite("Data Source=demo.db").Options);
await context1.Database.EnsureDeletedAsync();
await context1.Database.EnsureCreatedAsync();
await context1.Items.AddAsync(new Item
{
Id = 1,
Name = "Something to start with"
});
await context1.SaveChangesAsync();
await using var context2 = new MyContext(new DbContextOptionsBuilder().UseSqlite("Data Source=demo.db").Options);
var existing = context2.Find<Item>(1);
var entry = context2.Entry(existing);
entry.CurrentValues.SetValues(new Item
{
Id = 1,
Name = "Something to start with"
});
entry.State.Should().Be(EntityState.Unchanged);
entry.CurrentValues.SetValues(new Item
{
Id = 1,
Name = "Updated now."
});
entry.State.Should().Be(EntityState.Modified);
Using Microsoft.EntityFrameworkCore.Sqlite and FluentAssertions.
I am trying to create a new user object with a specific Role. The "Role" is an existing entity in EF. I have googled, and stackoverflowed until I am blue in the face, and I have tried all the stuff that seems to be working for everyone else. But when I try to save my new user object, it first tries to create a new "Role", instead of just creating the new user object with a reference to the existing Role.
What am I doing wrong?
Role myRole = new Role { ID = myUser.Role.ID };
myObjectContext.Roles.Attach(myRole);
myUser.Role = myRole;
if (myUser.ID == 0)
{
myObjectContext.Users.AddObject(myUser);
}
else
{
if (myUser.EntityState == System.Data.EntityState.Detached)
{
myObjectContext.Users.Attach(myUser);
}
myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
}
myObjectContext.SaveChanges(SaveOptions.None);
EDIT - AFTER MORE TESTING...
Ok.. so I have discovered some portion of the "cause" anyway. I still don't know why it does this and need help.
Basically, there are two sets of data I am attaching to my new User object. One is the "Role" which is a FK to a Role table that contains the Role. This shows up as a navigation property on the User like "User.Role".
The second set of data is a collection of objects called "FIPS", which are a many-to-many relationship between the User and another table called FIPS. There is a relationship table between them, that simply contains two columns, each a foreign key to User and FIPS, respectively. The FIPS for a user are also a navigation property that is referenced like "User.FIPS".
Here is the whole code showing the assignment of the FIPS and Role to the User object prior to saving the context.
List<string> fipsList = new List<string>();
foreach (FIPS fips in myUser.FIPS)
{
fipsList.Add(fips.FIPS_Code);
}
myUser.FIPS.Clear();
foreach (string fipsCode in fipsList)
{
FIPS myFIPS = new FIPS { FIPS_Code = fipsCode };
myObjectContext.FIPSCodes.Attach(myFIPS);
myUser.FIPS.Add(myFIPS);
}
Role myRole = new Role { ID = myUser.Role.ID };
myObjectContext.Roles.Attach(myRole);
myUser.Role = myRole;
if (myUser.ID == 0)
{
myObjectContext.Users.AddObject(myUser);
}
else
{
if (myUser.EntityState == System.Data.EntityState.Detached)
{
myObjectContext.Users.Attach(myUser);
}
myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
}
myObjectContext.SaveChanges(SaveOptions.None);
I set up my watch to check the status of "myObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added)" to see when things were being added to this.
As soon as the first Related object is added to the User object, the second Related object that hasn't yet been attached to the context, is added to the context with an EntityState of "Added".
.... Gonna see if there is a way to avoid attaching the related entities to the User entity until after they have all been attached to the context.
--FOLLOWUP--
Ok.. well I changed the order of the code so that the related entities were attached to the context before being assigned to the User entity.. but as soon as the first related entity is assigned, the second related entity is shown as "added" in the ObjectStateEntries.
So, then I changed it to the following order:
Attach all related entities to context.
Remove existing relationships on the user object to related entity
types.
Assign related entities to user entity.
Save user entity.
And.. now.. it works.. omg it works... ! =)
It's been a while since I wrote the code below, but I vaguely recall running into the same problem and it was occurring because the role being added was currently being tracked by the context, so attaching the stub has the effect of adding a new role with the same Id.
In the following code, I check the ChangeTracker first and use an existing entry if the role is being tracked.
// add roles that are in dto.Roles, but not in resource.Roles
// use the change tracker entry, or add a stub role
var rolesToAdd = fromDto.Roles.Where(r => !toResource.Roles.Any(role => role.Id == r)).ToList();
var roleEntries = dbContext.ChangeTracker.Entries<Role>();
foreach (var id in rolesToAdd)
{
var role = roleEntries.Where(e => e.Entity.Id == id).Select(e => e.Entity).FirstOrDefault();
if (role == null)
{
role = new Role { Id = id };
dbContext.Set<Role>().Attach(role);
}
toResource.Roles.Add(role);
}
Why are you creating a new instance of your Role entity if it already exists in the database?
Anyway, if you want to manually attach your new instance to the context, it should work if the ID of the attached instance exists in the database. But in your case the following lines are a bit strange:
Role myRole = new Role { ID = myUser.Role.ID };
myObjectContext.Roles.Attach(myRole);
myUser.Role = myRole;
You first create a new Role that has an ID that comes from an existing Role instance (myUser.Role) then you attach your new instance then finally you affect again your instance to the user it comes from.
There's definitely something wrong here.
If your Role already exists (and it appears to be the case here as you wrote myUser.Role.ID on the first line, so I assume), why are you creating a new instance.
Drop those 3 lines.
Get your Role from the database. Then affect the Role that comes from the database to the myUser.Role property.
This is how I did it in my case.
Its a similar case where Item contains ICollection<Attribute> .Here no update is done , adding already existing attribute to the item is needed.
First I looped through each attribute inside the item.
I had to first detach it from the local
context.Set<Model.Attribute>().Local
.Where(x => x.Id == attr.Id)
.ToList().ForEach(p => context.Entry(p).State = EntityState.Detached);
Then I attached .
context.Set<Model.Attribute>().Attach(attr);
Then I reloaded the datas to it .
context.Entry(attr).Reload();
Try using this instead of the first three lines (which shouldn't be necessary at all, if the user object already knows it's role's ID and is discarded anyway):
int id = myUser.Role.ID; // Role should be NULL, if the user is actually new...
// could it be that you wanted to write myUser.RoleID?
Role myRole = myObjectContext.Roles.FirstOrDefault(x => x.ID == id);
myUser.Role = myRole;