简体   繁体   English

实体框架(4)外键关系问题

[英]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. 用户名实体,Int64作为ID和其他一些字段。

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. 具有Int64作为ID的消息实体和通过1用户名链接到用户名实体的一些其他字段可以具有0到多个消息关系。

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? 但是我想将我在代码中生成的消息实体(新的Message()等)与用户名相关联,我将如何使用存储库和两个不同的objectcontexts进行此操作?

I got it working via not using a repository via: 我通过以下方式使用存储库来实现它:

usernameEntity.Messages.Add(msg);

Anyone 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: 如果在EFv4中建模了真正的外键关系,您还可以使用:

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

您需要一个跨多个存储库的工作单元 - 并负责提交对数据库的更改。

我在同一个实体上下文之上使用存储库模式,因此您可以轻松地在存储库之间共享对象。

If it is a one to many relationship, then you message entity should have a username id in it. 如果它是一对多关系,那么您的消息实体应该有一个用户名id。 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. 您可以使用用户名id在消息实体存储库ObjectContext中查找用户对象,并将消息添加到用户,然后保存更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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