我如何将同一个表中的2个外键定义到同一个列表但不同的实体

时间:2016-03-05 19:56:55

标签: c# entity-framework

我希望UserMessage实体点与ReciverIdFKSharedManWoman实体,SenderIdFK到另一个SharedManWoman实体

public class SharedManWoman
{
    public List<UserMessage> UserMessages { get; set; }
}

public class UserMessage
{      
        [Key]
        public long Id { get; set; }

        [ForeignKey("UserMessages")]
        public long SenderIdFK { get; set; }
        [InverseProperty("UserMessages")]
        public virtual SharedManWoman UserMessages { get; set; } 

        [ForeignKey("UserMessages")]
        public long ReciverIdFK { get; set; }
        [InverseProperty("UserMessages")]
        public virtual SharedManWoman UserMessages { get; set; } 
}

1 个答案:

答案 0 :(得分:1)

嗯,首先,你不能拥有两个同名的属性。

但是,在至少一个属性上使用以下流畅的api应该可以完成这项工作:

modelBuilder.Entity<UserMessage>()
   .HasOptional(t => t.UserMessages)
   .WithMany()
   .WillCascadeOnDelete(false);

修改

如果您想使用注释执行此操作,则应执行以下操作。请注意,您的SharedManWoman对象需要Id。而且,就目前而言,SharedManWoman几乎没用,因为它没有自己的任何属性。

public class SharedManWoman {
   public long Id { get; set; }

   [InverseProperty("Sender")]
   public ICollection<UserMessage> SenderMessages { get; set; }

   [InverseProperty("Receiver")]
   public ICollection<UserMessage> ReceiverMessages { get; set; }
}

public class UserMessage {

   [Key]
   public long Id { get; set; }

   // Note that these are NULLABLE
   public long? SenderIdFK { get; set; }
   public long? ReceiverIdFK { get; set; }


   [ForeignKey("SenderIdFK")]
   public virtual SharedManWoman Sender { get; set; }

   [ForeignKey("ReceiverIdFK")]
   public virtual SharedManWoman Receiver { get; set; }
}

More Info Here