Entity Framework/.Net 4.0: POCO and saving many to one relationships
How do I have to set up a property so that when using SaveChanges, the many to one relationship is saved and I don't get the: INSERT statement conflicted with the FOREIGN KEY constraint... error.
Pretty simple, I have an Ad and an AdType where there are many Ads to one AdType. There is a property on Ad:
public class Ad
{
public Int32 AdTypeId { get; set; }
public virtual AdType AdType { get; set; }
}
To cover this relationship.
When I do this:
someAd.AdType = someAdType;
The property is set ju开发者_运维问答st fine, but the AdTypeId is not. No worries though since I would assume this would be ok to save.
context.SaveChanges();
Problem is at this point it is trying to save the 0 value in the AdTypeId column (Causing a foreign key issue) instead of using the object assigned AdType property to figure out what it should insert into the AdTypeId column.
Things I know:
- At this point someAdType is persisted/has an id.
- The AdType property is set correctly.
- The AdTypeId is 0.
- There is a foreign key relationshipin the database.
- AdTypeId is a primary key.
- I have deferred/lazy loading set to true
I haven't really tried changing the AdType since it is set up to allow lazy loading.
Ok looks like because I am using the non proxied (Made that word up... Yah) "Snapshot based Change Tracking" approach, the system has no real idea that it's changed.
In this example, Customer is a pure POCO type. Unlike with EntityObject or IPOCO based entities, making changes to the entity doesn’t automatically keep the state manager in sync because there is no automatic notification between your pure POCO entities and the Entity Framework. Therefore, upon querying the state manager, it thinks that the customer object state is Unchanged even though we have explicitly made a change to one of the properties on the entity.
Got that from here
So in order to make sure it knows to check to see if there has been a change I have to use the AcceptAllChangesAfterSave option with the SaveChanges method.
context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
And it works. Hopefully I understand it correctly...
精彩评论