我的 DbContext 中有用户实体。我想要的是用户应该能够为彼此提供参考/发表评论,因此我创建了参考实体。
public class Reference
{
public virtual User By { get; set; } // user who leaves a reference
public virtual User To { get; set; } // user who has given a reference
public string Opinions { get; set; }
}
用户实体中的
public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given
public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given
我应该怎么做才能使它与DataAnnonations或FluentAPI一起使用,或者您将如何解决这个问题并解决?
答案 0 :(得分:0)
你需要做这样的事情:
public class Reference
{
public int ReferenceId { get; set; }
public int ByUserId { get; set; }
public virtual User By { get; set; } // user who leaves a reference
public int ToUserId { get; set; }
public virtual User To { get; set; } // user who has given a reference
public string Opinions { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given
public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given
}
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Reference> References { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Reference>()
.HasRequired(x => x.By)
.WithMany(x => x.ReferencedBy)
.HasForeignKey(x => x.ByUserId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Reference>()
.HasRequired(x => x.To)
.WithMany(x => x.ReferencedTo)
.HasForeignKey(x => x.ToUserId)
.WillCascadeOnDelete(false);
}
}