首页 > 解决方案 > 与实体框架的一对多关系

问题描述

在我的项目(Asp.net Core Web Api)中,我有表“卡车”和“用户帐户”,具有一对多的关系。

[Table("UserAccount")]
public class UserAccount : BaseClass
{
    // Foreign Keys
    [ForeignKey(nameof(UserAccountType))]
    public int UserAccountTypeId { get; set; } 
    [ForeignKey(nameof(Gender))]
    public int GenderId { get; set; }
    [ForeignKey(nameof(Truck))]
    public int TruckId { get; set; }

    // Properties
   
    public string LastName { get; set; }
    
    public string FirstName { get; set; }
    
    public string UserName { get; set; }
    
    [DataType(DataType.EmailAddress)]
    public string Mail { get; set; }
    public string Login { get; set; }
   
    [DataType(DataType.Password)]
    public string Password { get; set; }

    // Navigation Properties
    [IgnoreDataMember]
    public virtual Gender Gender { get; set; }
    //public virtual Truck Truck { get; set; }
    [IgnoreDataMember]
    public virtual UserAccountType UserAccountType { get; set; }
    
    public Truck Truck { get; set; }
}

[Table("Truck")]
public class Truck : BaseClass
{
    // Foreign Keys

    // Properties
    
    [Column(Order = 3)]
    public string Name { get; set; }
    
    [DataType(DataType.EmailAddress)]
    [Column(Order = 4)]
    public string Mail { get; set; }
    [Column(Order = 5)]
    public string Phone { get; set; }
    [Column(Order = 6)]
    public string VATNumber { get; set; }

    // Navigation Properties
    public virtual ICollection<TruckFoodType> TruckFoodTypes { get; set; }

    public virtual ICollection<TruckOption> TruckOptions { get; set; }

    public ICollection<UserAccount> UserAccounts { get; set; }
}

在我的 ApplicationDbContex 文件中的 OnModelCreation 方法中,我有这个来创建一对多的关系:

modelBuilder.Entity<UserAccount>()
            .HasOne<Truck>(u => u.Truck)
            .WithMany(t => t.UserAccounts)
            .HasForeignKey(u => u.TruckId);

但是当我尝试填充 UserAccount 表时,我收到此错误消息:“合并指令与“FK_User_Account_TruckId”冲突。此冲突发生在数据库 xxx 表 dbo.Truck 列 ID 中”(对不起,来自法语翻译)

我不明白为什么。有人可以帮助我吗?谢谢

标签: entity-framework-core

解决方案


好吧,愚蠢的错误。在某些情况下,用户帐户表中的 TruckId 字段可以为空。所以我加了一个“?” 像这样的字段:public int? TruckId { get; set; }抱歉给您带来不便


推荐阅读