0

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

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

在模型生成期间检测到一个或多个验证错误:

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'LogonInformation' 没有定义键。定义此 EntityType 的键。

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

4

1 回答 1

0

您的例外是抱怨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);
}
于 2013-03-29T04:01:29.130 回答