【问题标题】:Create primary key with Entity Framework 6使用 Entity Framework 6 创建主键
【发布时间】:2016-01-31 09:01:58
【问题描述】:

我已经检查了文档,这里有多个关于 SO 的问题,但没有任何作用,但它应该。在我的课下

public class Player
{
    [Key]
    public int PlayerId;

    public void SetId(int id)
    {
        this.PlayerId = id;
    }

    public int GetId()
    {
        return this.PlayerId;
    }

    protected String name;

    public void SetName(String name)
    {
        this.name = name;
    }

    public String GetName()
    {
        return this.name;
    }
}

如您所见,我使用的是命名约定,我什至添加了 [Key],但当我进行迁移时,我仍然收到

Player: : EntityType 'Player' 没有定义键。定义键 此实体类型。 Players: EntityType: EntitySet 'Players' 是基于 键入没有定义键的“播放器”。

发生了什么?为什么这不起作用?

【问题讨论】:

    标签: c# .net entity-framework entity-framework-6 entity-framework-migrations


    【解决方案1】:

    你需要使用auto properties

    public int PlayerId { get; set; }
    

    你的get/set方法看起来像Java,在C#中我们通常使用内联get/set


    更新: 如果你想使用受保护的属性,你可以使用下面的代码

    // protected property
    protected int PlayerId { get; set; }
    // protected get
    public int PlayerId { protected get; set; }
    // protected get
    public int PlayerId { get; protected set; }
    

    【讨论】:

    • 好的,但是如果我想使用受保护的字段怎么办?是的,我是 Java 类型的人;)我将每个字段都设置为公共的约定对我来说有点奇怪
    【解决方案2】:

    我从未见过这样的声明。在我看来像 java :) 尝试将 PlayerId 声明为属性,而不是公共字段。

    public int PlayerId { get; set; }
    

    您不需要 GetId 和 SetId 之类的方法。

    如果您想使用访问说明符为受保护或私有的属性,那么您需要在配置类中说明:

    public class Player
    {
        public int PlayerId { get; set; }
    
        protected string Name { get; set; }
    
        public class PlayerConfiguration : EntityTypeConfiguration<Player>
        {
            public PlayerConfiguration()
            {
                Property(b => b.Name);
            }
        }
    }
    

    【讨论】:

    • 好的,但是如果我想使用受保护的字段怎么办?是的,我是 Java 类型的人;)我将每个字段都设置为公共的约定对我来说有点奇怪
    • @Fixus 这不是一个字段,它是一个属性。
    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2018-08-12
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多