作为外键的主键抛出重复的定义异常

时间:2012-04-04 20:15:46

标签: c# entity-framework entity-framework-4 fluent

我正在使用Enterprise Framework 4.3.1及其Fluent API来设置映射到现有数据库的实体。

我有一个非常特殊的情况,一个关联表,它的主键是,同时,它们的父表的两个外键。

我得到的错误是:

Schema specified is not valid. Errors: 
(68,6) : error 0019: Each property name in a type must be unique. Property name 'ProductId' was already defined.
(69,6) : error 0019: Each property name in a type must be unique. Property name 'PropertyId' was already defined.

我的表格是这样的:

Products (ProductId, ...)
ProductProperties (ProductPropertyId, ...) // does not depend on Product!
DefaultPropertyValues (ProductId (FK1, PK), ProductPropertyId (FK2, PK), DefaultValue)

这是我设置该特定实体的代码:

//table mapping
modelBuilder.Entity<DefaultPropertyValue>().ToTable("DefaultPropertyValues", "dbo");

//not null value
modelBuilder.Entity<DefaultPropertyValue>().Property(d => d.DefaultValue).IsRequired();
//primary key
modelBuilder.Entity<DefaultPropertyValue>().HasKey(d => new { d.ProductId, d.ProductPropertyId });

//foreign key 1 -- see helper method
SetupGenericOneToManyForeignKey<DefaultPropertyValue, Product>(modelBuilder, d => d.Product, "ProductId");
//foreing key 2 -- see helper method
SetupGenericOneToManyForeignKey<DefaultPropertyValue, ProductProperty>(modelBuilder, d => d.ProductProperty, "ProductPropertyId");

//helper method
private CascadableNavigationPropertyConfiguration SetupGenericOneToManyForeignKey<TDependent, TParent>(DbModelBuilder modelBuilder, Expression<Func<TDependent, TParent>> foreignKeyField, string dbForeignKeyField) where TDependent: class where TParent: class
{
    return modelBuilder.Entity<TDependent>().HasRequired<TParent>(foreignKeyField).WithMany().Map((m) => m.MapKey(dbForeignKeyField));
}

所以,我的问题是......我做错了什么?

1 个答案:

答案 0 :(得分:2)

...如果我做对了,你要做的事情应该是这样的......

public class Product
{
    public int ProductId { get; set; }
    public virtual ICollection<DefaultPropertyValue> DefaultPropertyValues { get; set; }
}
public class ProductProperty 
{
    public int ProductPropertyId { get; set; }
    public virtual ICollection<DefaultPropertyValue> DefaultPropertyValues { get; set; }
}
public class DefaultPropertyValue 
{
    public int ProductId { get; set; }
    public int ProductPropertyId { get; set; }
    public Product Product { get; set; }
    public ProductProperty ProductProperty { get; set; }
}
...
modelBuilder.Entity<DefaultPropertyValue>()
    .HasKey(i => new { i.ProductId, i.ProductPropertyId });

modelBuilder.Entity<DefaultPropertyValue>()
    .HasRequired(i => i.Product)
    .WithMany(u => u.DefaultPropertyValues)
    .HasForeignKey(i => i.ProductId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<DefaultPropertyValue>()
    .HasRequired(i => i.ProductProperty)
    .WithMany(u => u.DefaultPropertyValues)
    .HasForeignKey(i => i.ProductPropertyId)
    .WillCascadeOnDelete(false);

......关键是HasForeignKey中的IMO,
希望这有帮助

注意:WillCascadeOnDelete当然是可选的,而WithMany可能是空的,但我通常会同样映射所有部分。