实体框架:脚手架时,请同时移除两个方向导航

时间:2019-10-04 07:50:46

标签: c# .net entity-framework .net-core entity-framework-core

当我使用Entity Framework Core搭建数据库时,如何防止双向属性?我只想允许1种方式的单向导航。有命令行脚手架参数吗?

在产品类别中,我要删除此属性

public virtual ICollection<CustomerTransaction> CustomerTransaction { get; set; }

基本上,只有客户交易记录才需要导航,因为它具有实际的外键。要删除最后一行,并且类似地具有1000多个表实体。需要EF脚手架命令行参数或自动化功能(可能使用Regex或其他工具)。

数据库:

create table dbo.CustomerTransaction(
    CustomerTransactionId int NOT NULL,
    ProductId int NULL,
    Quantity int NULL,
    CustomerLastName varchar(255) NULL,
    constraint PK_CustomerTransactionId primary key clustered (CustomerTransactionId ASC))

alter table dbo.CustomerTransaction add constraint fk_CustomerTransaction_Product_ProductId FOREIGN KEY(ProductId) REFERENCES dbo.Product (ProductId)

实体框架:

public partial class CustomerTransaction
{
    public int CustomerTransactionId { get; set; }
    public int? ProductId { get; set; }
    public int? Quantity { get; set; }
    public string CustomerLastName { get; set; }

    //Keep this line since it has the foreign key
    public virtual Product Product { get; set; }
}


public partial class Product
{
    public Product()
    {
        CustomerTransaction = new HashSet<CustomerTransaction>();
    }

    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal? Amount { get; set; }

    // REMOVE THIS LINE
    public virtual ICollection<CustomerTransaction> CustomerTransaction { get; set; }
}

结果:

只希望这种方式可用

storeDbContext.CustomerTransaction.Include(c => c.Product).ToListAsync()

不是这样,

storeDbContext.Product.Include(c => c.CustomerTransaction).ToListAsync()

使用EF Core 2.2,

0 个答案:

没有答案