DDan
DDan

Reputation: 8276

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!

Upvotes: 0

Views: 64

Answers (1)

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

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

Upvotes: 1

Related Questions