如何强制EF Core使用这个关系目标的属性的支持字段

时间:2018-06-15 18:08:49

标签: c# entity-framework-core

我想将一个属性配置为关系的目标,但我不希望在实现对象时EF使用getter或setter,因为我在那里有一些业务逻辑。

DispatchItem.cs:

public class DispatchItem {
    private PurchaseOrderItem _purchaseOrderItem;

    public PurchaseOrderItem PurchaseOrderItem {
        get => _purchaseOrderItem;
        set {
            _purchaseOrderItem = value;
            throw new Exception("This shouldn't be called");
        }
    }
    public Guid? PurchaseOrderItemId { get; set; }

}

我已经配置了这样的支持字段(DBContext.cs):

modelBuilder.Entity<DispatchItem>().Property(di => di.PurchaseOrderItem).UsePropertyAccessMode(PropertyAccessMode.Field);
modelBuilder.Entity<DispatchItem>().Property(di => di.PurchaseOrderItemId).HasColumnName("purchase_order_item_id");
modelBuilder.Entity<DispatchItem>().HasOne(di => di.PurchaseOrderItem).WithMany(poi => poi.DispatchItems).HasForeignKey(di => di.PurchaseOrderItemId);

但它抛出:

Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll
The navigation property 'PurchaseOrderItem' cannot be added to the entity type 'DispatchItem' because a property with the same name already exists on entity type 'DispatchItem'.

如果删除UsePropertyAccessMode语句,则在实现对象而不是支持字段时使用setter。

0 个答案:

没有答案