entity-framework - EF 代码优先 : Primary Key same as Foreign Key

标签 entity-framework ef-code-first fluent-interface

我有两个类(class)

public class Product
{
    public Guid Id { get; set; }
    public string ProductDetails { get; set; }
}

public class SpecialProductDetails
{
    public Guid Product_Id { get; set; } // PK and FK to Product class
    public string SpecialName { get; set; }
    public string SpecialDescription { get; set; }

    public virtual Product Product { get; set; }
}

SpecialProductDetailsProduct 类 1-1 映射并且是可选的。它共享相同的主键和外键。

在 Fluent API 中,我像这样映射这种关系(在 SpecialProductDetails 中)

public SpecialProductDetails()
{
    HasKey(p => p.Product_Id);
    HasRequired(p => p.Product).WithMany().HasForeignKey(p => p.Product_Id).WillCascadeDelete(true);
}

这在尝试生成数据库时给了我这个错误

\tSystem.Data.Entity.Edm.EdmAssociationEnd::多重性在关系“SpecialProductDetails_Product_Source”中的角色“SpecialProductDetails_Product_Source”中无效。因为Dependent Role是指关键属性,所以Dependent Role的重数上限必须是'1'。

如何在 EF Code First 上将列设置为 PK 和 FK?

最佳答案

我很确定你已经解决了这个问题,但我遇到了同样的问题,我找到的解决方案是:

 public SpecialProductDetails()
    {
        HasKey(p => p.Product_Id);
        HasRequired(p => p.Product).WithOptional();
    }

“值得注意的是,当我们使用 Fluent API 映射一对一关联时,我们不需要像使用 HasForeignKey 方法映射一对多关联时那样指定外键。由于 EF 只支持一对一的主键关联,它会自动在数据库中创建主键上的关系。”

http://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations之后

关于entity-framework - EF 代码优先 : Primary Key same as Foreign Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15061867/

相关文章:

entity-framework - Azure 部署连接字符串

c# - Asp.Net MVC 5 应用程序中所有模型的 Models.ApplicationDbContext?

c# - 用于更改列数据类型的 EF 迁移

entity-framework - EF Code First DropCreateDatabaseIfModelChanges 的最低数据库权限

c# - Fluent APIs - 返回这个还是新的?

c# - 确保进行调用以结束方法链

silverlight - MVVMLight、Silverlight、 Entity Framework

c# - EF5 代码优先 - 具有额外字段的多对多

c# - EF 中 IDatabaseInitializer 的正确用法是什么?

python - 与 Python 的流畅界面