[英]Entity Framework code first Fluent mapping
我有兩張桌子
現在,StoreOrder具有許多StoreOrderItems,StoreOrderItem具有一個StoreOrder(簡單的一對多關系)
public class StoreOrderItemMap : EntityTypeConfiguration<StoreOrderItem>
{
public StoreOrderItemMap()
{
this.ToTable("StoreOrderItem");
this.HasKey(op => op.Id);
this.Property(op => op.StoreOrderId).HasColumnName("order_id");
...
this.HasRequired(so => so.StoreOrder)
.WithMany(soi => soi.StoreOrderItems)
.HasForeignKey(so => so.StoreOrderId);
}
}
public class StoreOrderMap : EntityTypeConfiguration<StoreOrder>
{
public StoreOrderMap()
{
this.ToTable("StoreOrder");
this.HasKey(op => op.Id);
....
}
}
public class StoreOrderItem
{
....
public virtual int StoreOrderId { get; set; }
....
public virtual StoreOrder StoreOrder { get; set; }
}
public class StoreOrder
{
....
private ICollection<StoreOrderItem> _storeOrderItems;
....
public virtual ICollection<StoreOrderItem> StoreOrderItems
{
get { return _storeOrderItems ?? (_storeOrderItems = new List<StoreOrderItem>()); }
set { _storeOrderItems = value; }
}
}
//The code which is used to add the configurations to the modelBuilder.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
System.Type configType = typeof(ContentMap); //any of your configuration classes here
var typesToRegister = Assembly.GetAssembly(configType).GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
注意我正在現有數據庫上運行此代碼,如何告訴EF不要選擇“ StoreOrder_Id”,而要使用現有列“ order_id”?
這是錯誤:
“ /”應用程序中的服務器錯誤。
無效的列名“ StoreOrder_Id”。
說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。
異常詳細信息:System.Data.SqlClient.SqlException:無效的列名“ StoreOrder_Id”。
幾天彎腰后才發現問題......
StoreOrder類中還有另一個屬性
public virtual IList<StoreOrderItem> NonVoucherOrderItems
{
get
{
return this.StoreOrderItems.Where(x => !x.IsVoucher()).ToList();
}
}
對此評估還為時過早,並造成了各種混亂,更改為
public virtual IEnumerable<StoreOrderItem> NonVoucherOrderItems
{
get
{
return this.StoreOrderItems.Where(x => !x.IsVoucher());
}
}
它立即起作用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.