Feras Salim Feras Salim - 2 months ago 10
C# Question

Duplicated one-to-many relationship Entity Framework

I have two entities user and notification as following

public class Notification
{
public virtual int? FromUserId { get; set; }
public virtual int? ToUserId { get; set; }
public virtual SystemUser FromUser { get; set; }
public virtual SystemUser ToUser { get; set; }
}

public class SystemUser
{
public virtual ICollection<Notification> SentNotifications { get; set; }
public virtual ICollection<Notification> RecievedNotifications { get; set; }
}


How to make Entity Framework to load notifications in
SentNotifications
list which is
FromUser
is the current user and load notifications in
ReceivedNotifications
list which is
ToUser
is the current user?

Answer

One way is using InverseProperty Data annotation. You can place the annotations on either end of the relationship (or both ends if you want).

public class Notification
{
    public int? FromUserId { get; set; }
    public int? ToUserId { get; set; }
    [InverseProperty("SentNotifications")]
    public virtual SystemUser FromUser { get; set; }
    [InverseProperty("RecievedNotifications")]
    public virtual SystemUser ToUser { get; set; }
}

The second way is using Fluent Api to configure your relationships explicitly. You could, for example, override OnModelCreating method of your context and add this code:

modelBuilder.Entity<Notification>()
  .HasOptional(l => l.FromUser )
  .WithMany(p => p.SentNotifications)
  .HasForeignKey(l=>l.FromUserId);

modelBuilder.Entity<Notification>()
  .HasOptional(l => l.ToUser )
  .WithMany(p => p.RecievedNotifications)
  .HasForeignKey(l=>l.ToUserId);;
Comments