Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework EF代码优先:主键与外键相同_Entity Framework_Ef Code First_Fluent Interface - Fatal编程技术网

Entity framework EF代码优先:主键与外键相同

Entity framework EF代码优先:主键与外键相同,entity-framework,ef-code-first,fluent-interface,Entity Framework,Ef Code First,Fluent Interface,我有两节课 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

我有两节课

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; }
}
SpecialProductDetails
Product
类1-1映射,是可选的。它共享相同的PrimaryKey和ForeignKey

在Fluent API中,我映射这种关系如下(在
SpecialProductDetails
中)

在尝试生成数据库时,这会导致此错误

\tSystem.Data.Entity.Edm.edmsociationEnd::多重性在关系“SpecialProductDetails\u Product\u Source”中的角色“SpecialProductDetails\u Product\u Source”中无效。因为依赖角色引用密钥属性,所以依赖角色的多重性上限必须为“1”


如何首先在EF代码中将列设置为PK和FK?

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

 public SpecialProductDetails()
    {
        HasKey(p => p.Product_Id);
        HasRequired(p => p.Product).WithOptional();
    }
“值得注意的是,当我们使用fluent API映射一对一关联时,我们不需要像使用HasForeignKey方法映射一对多关联时那样指定外键。由于EF仅支持主键上的一对一关联,因此它将在数据库中自动创建主键上的关系。”


查看这篇文章后:@lc如果我使用.WithOptional(),那么我如何指定FK?是的,在一对一关系中,我不必指定
FK
,因为它已经被认为是“PK”
 public SpecialProductDetails()
    {
        HasKey(p => p.Product_Id);
        HasRequired(p => p.Product).WithOptional();
    }