开发者

Entity Framework (4) Foreign key relationship question

Lets say I have:

A username entity, with a Int64 as the ID and a few other fields.

A message entity, with a Int64 as the ID and a few other fields linked to the username entity via a 1 username can have 0 to many messages relationship.

I have two repositories (basic all, add, delete, save methods) for username and message entities.

But I want to associate a message entity that I generate in code (new Message() etc) with a username how would I do this with a repository and across two different objectcontexts?

I got it working via not using a repository via:

usernameEntity.Messages.Add(msg);

Anyone开发者_StackOverflow社区 got any hints, rather confused as if I could split this type of logic into two different repositories.


You will simply call:

var user = repository.GetUserById(id);
user.Messages.Add(new Message(...));
Save(); // I don't know how do you save changes.

Your repositories should share a single context for one unit of work (a business transaction). You should have some method (Save, Commit or whatever else) which will save changes made on entities loaded from all repositories. This is usually handled by a separate class implementing the unit of work pattern which wrapps context and is shared among repositories. Saving changes is called on unit of work instead of repository. There is plenty of related questions to this problem.

In case of real foreign key relationship modeled in EFv4 you can also use simply:

var message = new Message(...);
message.UserId = id; // Foreign key property exposed on Message entity
repository.Insert(message);
Save();


You need a unit of work that spans multiple repositories - and is responsible for committing changes to the database.


I use the repository pattern on top of the same entity context so you can share objects between repositories easily.


If it is a one to many relationship, then you message entity should have a username id in it. You could use the username id to look up the user object in your message entity repository ObjectContext and add the message to the user, then save your changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜