简体   繁体   中英

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. How do I implement this? I am Using Entity-Framework 6 in MVC Web-Application. 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

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);
}

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