简体   繁体   中英

Entity Framework saving the same linked entity over and over again

I'm coming from NHibernate and I'm quite confused about Entity Framework's handling of linked entities.

I have a model called Post. Each post have a linke entity Account, which tells which account created the post.

When I create a post, I use the following code:

var post = new Post();
post.Account = GetAccount();
db.Posts.Add(post);
db.SaveChanges();

What GetAccount() does is getting the current user's account from the database based on a cookie. It also caches this for the current request (asp.net) so it doesn't have to be fetched multiple times.

Now, this causes a new Account (identical but with new ID) to be inserted for each post I save. I've implemented Equals and GetHashCode for Account which would have been sufficient for NHibernate, but not for Entity Framework, right?

What am I missing?

You need to make sure your using the same DataContext class when performing this operation as it will not register this as an existing entity. Hence why you are getting replicated accounts each time you save.

*See comments on initial question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM