我在一个项目中有两个实体:SupplierFinishingItem
和ProductOptionListItem
。
qazxsw poi通过导航属性引用另一个。
当我尝试创建引用ProductOptionListItem
的1个ProductOptionListItem
时,它可以工作并将关系保存在数据库中。
但是当我尝试创建2个或更多引用相同SupplierFinishingItem
的ProductOptionListItem
时,只有第一个实体将关系保存到数据库中。其他人用SupplierFinishingItem
参考保存。
我设法在最小的控制台应用程序中重现它:
null
运行此代码后生成的数据库如下:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace relationship_test
{
class Program
{
static void Main(string[] args)
{
using (var db = new DatabaseContext())
{
var finishing = new SupplierFinishingItem { Name = "Finishing"};
db.Finishings.Add(finishing);
db.SaveChanges();
db.Options.Add(new ProductOptionListItem { Name = "Option 1", SupplierFinishingItem = finishing });
db.Options.Add(new ProductOptionListItem { Name = "Option 2", SupplierFinishingItem = finishing });
db.Options.Add(new ProductOptionListItem { Name = "Option 3", SupplierFinishingItem = finishing });
db.SaveChanges();
}
}
}
public class DatabaseContext : DbContext
{
public DbSet<ProductOptionListItem> Options { get; set; }
public DbSet<SupplierFinishingItem> Finishings { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=entity-test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductOptionListItem>()
.HasOne(p => p.SupplierFinishingItem)
.WithMany(s => s.UsedBy)
.HasForeignKey(p => p.SupplierFinishingItemId)
.OnDelete(DeleteBehavior.Restrict);
}
}
public class ProductOptionListItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public Guid? SupplierFinishingItemId { get; set; }
public SupplierFinishingItem SupplierFinishingItem { get; set; }
}
public class SupplierFinishingItem
{
private HashSet<ProductOptionListItem> _usedBy;
public Guid Id { get; set; }
public string Name { get; set; }
public IEnumerable<ProductOptionListItem> UsedBy => _usedBy?.ToList();
}
}
如你所见,只有有Option 1
,另外两个是SupplierFinishingItemId
。
我在这里错过了什么?
该问题是由集合导航属性的实现引起的:
NULL
从getter返回新的列表实例会以某种方式混淆EF Core导航属性修正代码并产生上述效果(甚至在`SaveChanges()调用之前)。
解决方案是修复实现以不在每次调用时返回新列表(无论如何,这被认为是属性getter的不良做法),例如:
public IEnumerable<ProductOptionListItem> UsedBy => _usedBy?.ToList();
或配置EF Core直接使用支持字段:
public IEnumerable<ProductOptionListItem> UsedBy => _usedBy ?? (_usedBy = new HashSet<ProductOptionListItem>());