entity-framework-core - 与实体框架的一对多关系
问题描述
在我的项目(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 中”(对不起,来自法语翻译)
我不明白为什么。有人可以帮助我吗?谢谢
解决方案
好吧,愚蠢的错误。在某些情况下,用户帐户表中的 TruckId 字段可以为空。所以我加了一个“?” 像这样的字段:public int? TruckId { get; set; }
抱歉给您带来不便
推荐阅读
- javascript - 将 pug 编译的内容附加到 pug 模板
- git - Visual Studio 2017 的多个 Git 存储库
- javascript - jsx 和 React 中的动态标签名称不传递道具
- php - 我无法在 wordpress 中使用 elementor 编辑我的主页
- gradle - gradle 中的自定义配置
- python - 在 Python 中使用带有 R 语法的 statsmodels.api 进行逻辑回归
- azure - Azure 应用程序网关中的失败请求列表
- pentaho - 如何使用 Pentaho 数据集成 (PDI) 将 Sqlite 数据传输到 Mysql?
- android - 使用谷歌浏览器远程调试我的安卓设备没有显示浏览器检查
- flutter - 如何从飞镖文件中调用graphQl“查询”