简体   繁体   English

使用Entity Framework 6创建主键

[英]Create primary key with Entity Framework 6

I've checked documentation, multiple questions here on SO and nothing work but it should. 我检查了文档,这里有关于SO的多个问题,没有任何帮助,但应该这样做。 Below my class 在我班下

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;
    }
}

As you can see I'm using the name convention, I even added the [Key] but still when I'm doing migration I receive 如您所见,我正在使用名称约定,甚至添加了[Key]但是在进行迁移时仍然收到

Player: : EntityType 'Player' has no key defined. 播放器::EntityType'Player'尚未定义键。 Define the key for this EntityType. 定义此EntityType的键。 Players: EntityType: EntitySet 'Players' is based on type 'Player' that has no keys defined. 播放器:EntityType:EntitySet“播放器”基于没有定义键的“播放器”类型。

What is going one ? 怎么回事? Why this is not working ? 为什么这不起作用?

you need to use auto properties 您需要使用auto properties

public int PlayerId { get; set; }

your get/set methods look like Java , in C# we usually use inline get/set 您的get / set方法看起来像Java ,在C#中,我们通常使用内联get/set


UPDATE : if you want to use protected properties, you can use the code below 更新 :如果要使用受保护的属性,可以使用下面的代码

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

I have never seen a declaration like this. 我从未见过这样的声明。 Looks like java to me :) Try to declare PlayerId as a property, not as a public field. 在我看来就像Java :)尝试将PlayerId声明为属性,而不是公共字段。

public int PlayerId { get; set; }

You dont need methods like GetId and SetId. 您不需要GetId和SetId之类的方法。

If you want to use properties having access specifier as protected or private then you need to tell that in your configuration class: 如果要使用访问说明为受保护或私有的属性,则需要在配置类中进行说明:

public class Player
{
    public int PlayerId { get; set; }

    protected string Name { get; set; }

    public class PlayerConfiguration : EntityTypeConfiguration<Player>
    {
        public PlayerConfiguration()
        {
            Property(b => b.Name);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM