【发布时间】:2011-08-03 06:53:14
【问题描述】:
我有这些课程:
public class Product
{
[Key]
public virtual int ProductId { get; set; }
public virtual string ProductName { get; set; }
public virtual string Category { get; set; }
public virtual IList<ProductPricing> ProductPriceList { get; set; }
[Timestamp]
public virtual byte[] Version { get; set; }
}
public class ProductPricing
{
// no ProductId here
public virtual Product Product { get; set; }
[Key]
public virtual int ProductPricingId { get; set; }
public virtual DateTime EffectiveDate { get; set; }
public virtual decimal Price { get; set; }
}
这是我的模型构建器:
modelBuilder.Entity<Product>().
HasMany(x => x.ProductPriceList)
.WithRequired()
.HasForeignKey(x => x.Product);
这是错误:
外键组件“产品”不是在 输入“产品定价”。验证它没有被明确排除 来自模型并且它是一个有效的原始属性。
更新
我已经尝试了以下,代码下方的相应错误
modelBuilder.Entity<Product>()
.HasMany(x => x.ProductPriceList)
.WithRequired();
{"无效的列名 'Product_ProductId1'。\r\n无效的列名 'Product_ProductId'。\r\n无效的列名'Product_ProductId1'。"}
modelBuilder.Entity<Product>()
.HasMany(x => x.ProductPriceList)
.WithRequired()
.Map(x => x.MapKey("ProductId"));
{"无效的列名'Product_ProductId'。"}
modelBuilder.Entity<Product>()
.HasMany(x => x.ProductPriceList)
.WithRequired(x => x.Product);
{"无效的列名 'Product_ProductId'。\r\n无效的列名 'Product_ProductId'。"}
modelBuilder.Entity<Product>()
.HasMany(x => x.ProductPriceList)
.WithRequired(x => x.Product)
.Map(x => x.MapKey("ProductId"));
{"违反多重性约束。角色 'Product_ProductPriceList_Source' 的关系 'TestEfCrud.Mappers.Product_ProductPriceList' 具有多重性 1 或 0..1."}
如果有帮助,这里是 DDL:
create table Product
(
ProductId int not null identity(1,1) primary key,
ProductName varchar(100) not null,
Category varchar(100) not null,
Version rowversion not null
);
create table ProductPricing
(
ProductId int not null references Product(ProductId),
ProductPricingId int identity(1,1) not null primary key,
EffectiveDate datetime not null,
Price decimal(18,6) not null
);
更新 2
我已经尝试过这个答案,它看起来与我的情况类似 bit,映射源自子实体 How to map parent column in EF 4.1 code first
但是,使用这个:
modelBuilder.Entity<ProductPricing>()
.HasOptional(x => x.Product)
.WithMany()
.Map(x => x.MapKey("ForeignKeyColumn"));
还有这个:
modelBuilder.Entity<ProductPricing>()
.HasRequired(x => x.Product)
.WithMany()
.HasForeignKey(x => x.Product);
两者都导致了这个错误:
{"无效的列名 'Product_ProductId1'。\r\n无效的列名 'Product_ProductId1'。\r\n无效的列名'Product_ProductId1'。"}
【问题讨论】:
标签: entity-framework mapping entity-framework-4.1