【发布时间】:2022-01-14 01:33:49
【问题描述】:
我正在尝试创建一个简单的一对多关系,但 Ef Core 不知何故无法识别它。我仍然是这方面的初学者,但我想我是按书本做的(完全定义了关系),所以我不明白为什么 EF Core 会抛出这个错误:
无法确定导航所代表的关系 'Insurance' 类型的'Asset.Insurance'。要么手动配置 关系,或使用“[NotMapped]”忽略此属性 属性或在“OnModelCreating”中使用“EntityTypeBuilder.Ignore”。
这是我的两个模型: 资产.cs
public class Asset
{
public int AssetId { get; set; }
public string AssetName { get; set; }
[ForeignKey("AssetTypeId")]
public int AssetTypeId { get; set; }
public AssetType AssetType { get; set; }
public ICollection<AssetValue> AssetTypeValues { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public string ProductNumber { get; set; }
public DateTime PurchaseDate { get; set; }
public decimal PurchasePrice { get; set; }
[ForeignKey("LocationId")]
public int? LocationId { get; set; }
public Location Location { get; set; }
[ForeignKey("InsuranceId")]
public int InsuranceId { get; set; }
public Insurance Insurance { get; set; }
[ForeignKey("OwnerId")]
public string? OwnerId { get; set; }
public AppUser Owner { get; set; }
[ForeignKey("InvoiceId")]
public int? InvoiceId { get; set; }
public Insurance Invoice { get; set; }
public string? ImagePath { get; set; }
public string? Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Insurance.cs
public class Insurance
{
public int InsuranceId { get; set; }
[ForeignKey("InsuranceTypeId")]
public int InsuranceTypeId { get; set; }
public InsuranceType InsuranceType { get; set; }
public string Insurer { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string? FilePath { get; set; }
public string? Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public ICollection<Asset> Assets { get; set; }
}
另外,如果我删除这个关系,只是为了测试,迁移仍然不起作用,并且会抛出有关资产模型中其他外键的错误。是不是因为我的外键太多,所以必须在 OnModelCreating 中定义?
编辑:ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<AppUser>
{
public DbSet<Asset> Assets { get; set; }
public DbSet<AssetType> AssetTypes { get; set; }
public DbSet<AssetProp> AssetProps { get; set; }
public DbSet<AssetValue> AssetValues { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyContact> CompanyContacts { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InsuranceType> InsuranceTypes { get; set; }
public DbSet<Insurance> Insurances { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
【问题讨论】:
标签: c# entity-framework asp.net-core entity-framework-core