【问题标题】:How to map a list of component in Entity Framework 5?如何在 Entity Framework 5 中映射组件列表?
【发布时间】:2013-03-29 14:19:48
【问题描述】:

我是 NHibernate 用户,NHibernate 允许我创建一个非常细粒度的模型。 我正在将一个应用程序从 NHibernate 移植到 Entity Framework。

NHibernate 允许我定义如下内容:

public class User : DomainEntity
{
    public virtual Name Name { get; set; }
    ...
    public virtual ICollection<LogonInformation> LogonInformations { get; set; }
}

public class Name
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

public class LogonInformation
{
    public virtual string Ip { get; set; }
    public virtual DateTime Date { get; set; }
}

其中 Name 和 LogonInformation 映射为 。 在特殊情况下,NHibernate 在创建数据库时,会在 LogonInformation 表中创建 UserId。 如何使用 EntityFramework 5 做到这一点? 我试过使用复杂类型,但它似乎不起作用,因为我仍然得到以下异常:

在模型生成过程中检测到一个或多个验证错误:

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'LogonInformation' 没有定义键。为此定义密钥 实体类型。

\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'LogonInformations' 基于类型 'LogonInformation' 没有 已定义键。

【问题讨论】:

    标签: entity-framework entity-framework-5


    【解决方案1】:

    您的例外是抱怨LogonInformation 没有主键。为了建立一个主键,您将属性Key 添加到您想成为主键的属性中,例如,如果Ip 是您的主键,您的代码将是:

    public class LogonInformation
    {
        [Key]
        public virtual string Ip { get; set; }
        public virtual DateTime Date { get; set; }
    }
    

    更新: 如果您无法更改LogonInformation,您可以使用 Fluent-API 设置其主键(我不喜欢这种方式,但它可以解决您的问题)。为此,您需要在上下文中重写 OnModelCreating 方法,如下所示:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<LogonInformation>().HasKey(logInfo => logInfo.Ip);
    }
    

    【讨论】:

    • 我不能像 NHibernate 那样告诉 EF 在“启动”期间添加 UserId 列吗?我无法更改 LogonInformation 类。
    • @cidico:我不知道 NHibernate,但在 EF Code-First 中,您必须设置主键属性的方式是将其命名为 Id 或添加 Key 属性。
    • @cidico:我编辑了我的答案,检查一下,如果这就是你要找的,请告诉我;)
    • 抱歉耽搁了!嗯,是这样的,但我不能使用 Ip 属性作为我的密钥(因为它有时会重复)。我需要做的与映射 IList 一样。这是一对多的,我需要从父级添加 Id。就像我不能将 Id 属性添加到字符串类型一样。我猜EF不支持它。 :(
    猜你喜欢
    • 2013-10-27
    • 2017-12-31
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多