简体   繁体   English

实体框架2同一2个实体之间的关系

[英]Entity Framework 2 Relation between same 2 entities

I am planning to have a model something like this: 我正计划建立一个类似这样的模型:

public class Message{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int MessageId { get; set; }

    public string Category { get; set; }
    [Required]
    public string Subject { get; set; }
    public string MessageBody { get; set; }

    // Sender IS ASSOCIATION TO UserProfile 0..1
    [ForeignKey("Sender")]
    public virtual int? UserId { get; set; }
    public UserProfile Sender { get; set; }

    // Recipients IS ASSOCIATION TO UserProfile 0..n
    public virtual ICollection<UserProfile> Recipients { get; set; }
}

So the message model would have 2 associations to the UserProfile Model with different multiplicity. 因此,消息模型将与具有不同多重性的UserProfile模型具有2个关联。 How do I implement this? 我该如何实施? I am Using Entity-Framework 6 in MVC Web-Application. 我在MVC Web应用程序中使用实体框架6。 Thanks! 谢谢!

You can just add to mapping two statements: 您只需添加两个映射语句即可:

HasOptional(c=>c.Sender).WithMany().HasForeignKey(c=>c.UserId);
HasMany(c=>c.Recepients).WithMany(c=>c.IncomingMessages);

I suppose that you have many to many relations between messages and recepients and one to many between sender and messages. 我想您在消息和接收者之间有多对多的关系,在发送者和消息之间有一对多的关系。

You should add this code to dbcontext class in overriden method 您应该将此代码添加到重写方法中的dbcontext类中

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Message>()
        .HasOptional(c=>c.Sender).WithMany().HasForeignKey(c=>c.UserId)
        .HasMany(c=>c.Recepients).WithMany(c=>c.IncomingMessages);
}

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

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