2

我对 EF 有一些映射问题。

这是我的课

public class User{
    public Guid Id { get; set; }
    // Fullname of the user account owner
    public string Name { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public Player Player { get; set; }
}

public class Player
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual User User { get; set; }
}

它工作正常,但现在我想在此类中创建导航属性 Player 和 User。我有这个流利的代码:

        modelBuilder.Entity<User>()
            .HasOptional(x => x.Player)
            .WithOptionalDependent(x => x.User)
            .Map(x => x.MapKey("Username"));

但我只收到此错误消息,我不知道出了什么问题。

类型中的每个属性名称都必须是唯一的。已定义属性名称“用户名”。

我的数据库设置看起来像类,在播放器表中名称是唯一的。它在 User 表中不是唯一的。用户可以在没有玩家的情况下存在,反之亦然。(实际上我不想在 Player 类中有任何 User 属性,但我认为这是一个要求?!)

4

4 回答 4

1

我认为这是在抱怨 UserName 已经是对象模型中的一个属性。请参阅 Map() 方法的文档:

来自http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.configuration.foreignkeynavigationpropertyconfiguration.map%28v=vs.103%29

将关系配置为使用未在对象模型中公开的外键属性。可以通过指定配置操作来自定义列和表。如果指定了空配置操作,则将按约定生成列名。如果在对象模型中公开了外键属性,则使用 HasForeignKey 方法。并非所有关系都支持在对象模型中公开外键属性。

于 2012-09-01T18:43:02.357 回答
0

移除 modelBuilder 代码并将 PrimaryKey 标记为依赖表上的 ForeignKey。例如,如果没有用户就不存在玩家:

public class User
{
    public Guid Id { get; set; }
    // Fullname of the user account owner
    public string Name { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }

    public Player Player { get; set; }
}

public class Player
{
    [ForeignKey("User")]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual User User { get; set; }
}

ForeignKey 属性告诉 EF 一对一的哪一侧是依赖的,允许它正确映射它。

于 2013-03-31T00:56:00.567 回答
0

If your columns in the database has the same name as the properties of your model you don't need to map the property ".Map(x => x.MapKey("Username"));" EF already mapped the property "Username" using the convention and is because of that the EF is complaining

于 2013-03-31T01:42:04.847 回答
0

与您的实体

...我只是喜欢反过来做:

modelBuilder.Entity<Player>()
    .HasRequired(i => i.User)
    .WithRequiredDependent(i => i.Player);

或者这个(可选):

modelBuilder.Entity<Player>()
    .HasRequired(i => i.User)
    .WithOptional(x => x.Player);
于 2013-03-31T02:30:32.623 回答