【问题标题】:EF-Code first complex type with a navigational propertyEF-Code 第一个具有导航属性的复杂类型
【发布时间】:2011-09-29 20:25:12
【问题描述】:

我的模特:

public class Country
{
    public int CountryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

public class Location
{
    public string Address { get; set; }

    public virtual int CountryId { get; set; }
    public virtual Country Country { get; set; }
}    

public class User{

    protected User()
    {
        Location = new Location();
    }

    public int UserId { get; set; }
    public Location Location { get; set; }

}

生成数据库时,我得到:

One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'Location' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Locations� is based on type �Location� that has no keys defined.

如何在复杂类型中拥有导航属性?如果我删除国家导航属性,它工作正常。

【问题讨论】:

    标签: entity-framework entity-framework-4.1 ef-code-first


    【解决方案1】:

    不支持复杂类型的导航属性(引用其他实体)。您必须将 Location 设为实体(具有自己的表)或从 Location 中删除导航属性 Country(并添加史蒂夫摩根提到的 [ComplexType] 属性)。

    编辑

    参考:http://msdn.microsoft.com/en-us/library/bb738472.aspx

    “复杂类型不能包含导航属性。”

    【讨论】:

    • 但是Location 类中的CountryID 整数呢?是否可以使其成为外键约束? (我有类似的问题,无法让它工作)
    • @Isak:不,这是不可能的。如果你想让它在数据库中 FK,你必须直接在数据库中进行,但 EF 不会反映它。
    • MSDN 上的复杂类型描述中直接提到了不支持这一点:msdn.microsoft.com/en-us/library/bb738472.aspx
    • @Ladislav:感谢您的参考!我已将其复制到答案中。
    • @LadislavMrnka:好的,谢谢。我有一半希望可以通过流畅的 API 在父类(即实际实体)上指定,但我猜不是(虽然我无法让它工作)
    【解决方案2】:

    EF 想要推断 Location 的主键,但不能。

    public int LocationId { get; set; } 添加到Location 类,它应该会很高兴。

    如果您想将Location 用作复杂类型,请使用[ComplexType] 属性对其进行注释。

    【讨论】:

    • 这将生成一个全新的表。我希望它是一个复杂的类型。
    猜你喜欢
    • 2016-01-09
    • 2012-01-26
    • 2016-03-16
    • 2014-10-15
    • 2016-10-10
    • 2022-07-18
    • 1970-01-01
    • 2017-06-26
    • 2014-01-20
    相关资源
    最近更新 更多