一个模型中的一个1-1关系和两个1-n关系

时间:2016-08-15 15:35:07

标签: c# sql entity relationship

我的WerehouseKey课程:

public class WerehouseKey
{
    [Key]
    public int WhKeyID { get; set; }

    (...)

    public virtual KeyRent KeyRent { get; set; }

    [Display(Name = "Magazyn")]
    public int WhID { get; set; }
    public virtual Werehouse Werehouse { get; set; }
}

用户类:

public class User
{
    [Key]
    public int UserID { get; set; }

    (...)

    public virtual ICollection<KeyRent> RUsers { get; set; }
    public virtual ICollection<KeyRent> GUsers { get; set; }
}

最后我的KeyRent类:

public class KeyRent
{
    [Key]
    public int WhKeyID { get; set; }

    (...)

    public virtual WerehouseKey WerehouseKey { get; set; }

    public int RUserID { get; set; }
    public virtual User RentingUser { get; set; }

    public int GUserID { get; set; }
    public virtual User GivingUser { get; set; }
}

我希望在1-1中有WerehouseKey和KeyRent之间的关系,它完美地工作,然后我希望它和用户之间在KeyRent中有两个1-n关系。基本上一个用户租用密钥,一个用户给出密钥,他们都可以租用/给出许多密钥。我有自己的OnModelCreating函数:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<KeyRent>()
            .HasKey(e => e.WhKeyID);

        modelBuilder.Entity<WerehouseKey>()
                    .HasOptional(s => s.KeyRent)
                    .WithRequired(ad => ad.WerehouseKey);

        modelBuilder.Entity<KeyRent>()
                .HasRequired<User>(s => s.RentingUser)
                .WithMany(s => s.RUsers)
                .HasForeignKey(s => s.RUserID);

        modelBuilder.Entity<KeyRent>()
                .HasRequired<User>(s => s.GivingUser)
                .WithMany(s => s.GUsers)
                .HasForeignKey(s => s.GUserID);

        modelBuilder.Entity<User>()
                .HasMany<KeyRent>(s => s.GUsers)
                .WithOptional(s => s.GivingUser)
                .HasForeignKey(s => s.GUserID);

        modelBuilder.Entity<User>()
                .HasMany<KeyRent>(s => s.RUsers)
                .WithOptional(s => s.RentingUser)
                .HasForeignKey(s => s.RUserID);
    }

问题在于,当我想添加迁移时,它会向我显示此错误

  

“在'WerehouseProject.Models.KeyRent'类型上声明的导航属性'GivingUser'已经配置了冲突的多重性。”

有人可以告诉我这里有什么问题以及如何修复它?

0 个答案:

没有答案