EF中2表之间的关系(null表示一对多)。 [英] ralationships between 2 table in EF (one to many on null).

查看:79
本文介绍了EF中2表之间的关系(null表示一对多)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我来到这里有一个与EF 4.3.1相关的问题。

在我的域名模型中我有2个型号:用户消息,每个都有一个主键,名为 Key

经过一些分析过程后我发现,我需要提供一些额外的功能来表示消息,有些用户已经阅读过了。



因此,我在我的用户模型中声明了新属性:

Hi guys,

I have come here with one question related to EF 4.3.1.
In my domain model I have 2 models: User and Message, each one has a primary key, called Key.
After some analyzing process I have figured out, that I need to provide some additional funcions to represent messages, were read by some user.

So as a result, I declared new property in my User model:

public virtual ICollection<Message> ReadMessages { get; set; }





事实上,我需要通过第三个表提供这两个域模型之间的链接,例如: ReadMessages



但有一点需要注意,这个表必须包含列,这些列将显示读取消息的时间。

另一个,用户无法阅读消息

)。



如何在EF中使用流畅的API实现这一目标?

也许EF中有一些经验丰富的人可以帮我解决这种联系。



我认为可以实现如下:



So in fact, I need to provide linking between these 2 domain models through a third table for example: ReadMessages.
(
But one thing to notice, this table must contain columns, which will display time when message was read.
And another one, user can have no read messages
).

How to achieve this with fluent API in EF??
Maybe there is some experienced people in EF, who can help me with such linking.

I think it can be achieved as follows:

public class MessangerUserMap:EntityTypeConfiguration<user>
{
  public MessangerUserMap()
  {
    this.HasMany(x => x.ReadMessages).WithRequired().Map(m =>
                {    m.ToTable("ReadMesssages").MapKey("UserKey");
                     ??? how to add column ReadTime to table ReadMessages!! 
                });
  }
}

推荐答案

我已经成功解决了这个问题。

这里的关键时刻是在这个域实体之间创建多对多关系。



因此,我已经注入了每个具体的域模型属性(集合相关实体)。

例如,在消息的域模型中,我注入了这样的属性:

I have successfully resolved such problem.
The crucial moment here was in creation of many-to-many relationships between this domain entities.

So as a result i have injected to each concrete domain model property(collection of related entity).
For example, in domain model of Message i have injected such property:
public virtual ICollection<user> UsersWhoRead {get;set;}</user>





关于映射,我添加了几行代码:



As concerns mappings, i have added few lines of code:

this.HasMany(x => x.ReadMessages).WithMany(x => x.UsersWhoRead)
            .Map(m => m.MapLeftKey("User_Key").MapRightKey("Message_Key").ToTable("UserReadMessage"));


这篇关于EF中2表之间的关系(null表示一对多)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆