我有两张桌子
现在,StoreOrder有许多StoreOrderItems,StoreOrderItem有一个StoreOrder(简单的1对多关系)
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'无效。
描述:执行期间发生了未处理的异常 当前的网络请求。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息:System.Data.SqlClient.SqlException:无效列 名称'StoreOrder_Id'。
答案 0 :(得分:1)
经过几天心灵弯曲后发现问题......
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());
}
}
它立即起作用了!