如何删除实体框架代码优先的多对多自动生成的表



我有三个实体产品供应商&合同,产品&每个供应商都有一个彼此的集合作为参考,该集合创建了一个ProductSupplier表。

为了在这个多对多关系上添加一个额外的属性,我创建了一个第三实体ProductForSupplier,它包含1个Product、1个Supplier和一个额外字符串property ProductNumber。

此外,我还创建了另一个实体ProductSupplierForContract,该实体持有一个ProductForSupplier&合同。当我为测试播种一些数据时,我可以观察到ProductSupplierForContract没有产品&供应商Id值,而它们存在于我的ProductForSupplier实体中,但Id没有记录的ProductForSupplierId。

我如何删除表ProductSupplierForContract中的这两个属性,因为我有包含这两个值的表的Id?

实体:

public class Product : BaseEntity // BaseEntity just holds an Id and a date
{
public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }
public ICollection<ProductForSupplier> ProductForSuppliers { get; set; }
}
public class Supplier : BaseEntity
{
public ICollection<ProductForSupplier> ProductForSuppliers { get; set; }
public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }
} 
public class Contract : BaseEntity
{
public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }
}
public class ProductForSupplier:BaseEntity
{
public string ProductNumber{ get; set; }
[Required]
public Product Product { get; set; }
[Required]
public Supplier Supplier { get; set; }
}
public class ProductSupplierForContract: BaseEntity
{
[Required]
public ProductForSupplier ProductForSupplier { get; set; }
[Required]
public Contract Contract { get; set; }
}

播种方法

protected override void Seed(TestDbContext context)
{
Supplier supplier1 = new Supplier("Microsoft");
context.Suppliers.Add(supplier1);         
Product product1 = new Product("test product 1");
context.Products.Add(product1);
Contract contract = new Contract("Contract 1");
context.Contracts.Add(contract);
ProductForSupplier pfs = new ProductForSupplier("123productNumber");
pfs.Supplier = supplier1;
pfs.Product = product1;        
context.ProductForSuppliers.Add(pfs);
ProductSupplierForContract psfc = new ProductSupplierForContract(pfs, contract);
context.ProductSupplierForContracts.Add(psfc);
base.Seed(context);
}

愚蠢的我,

我删除了我的供应商&产品实体,这给了我想要的东西,因为这就是创建这些东西的原因。

删除了两个实体中的此行:

public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }

我有另一个解决方案,在DbContext中,我们有OnModelCreating方法,在构建模型时,我们只使用Ignore。例如:

modelBuilder.Entity<Product>(b =>
{
b.Ignore(p => p.ProductSupplierForContracts);
});
modelBuilder.Entity<Supplier>(b =>
{
b.Ignore(p => p.ProductSupplierForContracts);
});

最新更新