Pergunta

I'm going in circles with either an in valid context type or undefined entity key. I have attached a copy of the longer error message. Just trying to create a test application that is connected to an existing db.

enter image description here

Here is the code - thanks in advance

    public class TestPerson
{
    int ID { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    string Hair { get; set; }
    string Race { get; set; }
    string Measurements { get; set; }
}

public class TestPersonContext : DbContext
{
    public DbSet<TestPerson> TestPersons { get; set; }
}
Foi útil?

Solução

You should set one of your properties as the primary key. In your case this will be the ID property:

public class TestPerson
{
    [Key]
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Hair { get; set; }
    public string Race { get; set; }
    public string Measurements { get; set; }
}

public class TestPersonContext : DbContext
{
    public DbSet<TestPerson> TestPersons { get; set; }
}

Btw why are all your properties private? It would be recommended to make all them publicly available, especially the primary key.

What is more there is something called Convention over Configuration which is used quite intensively in Entity Framework. One of the conventions is the Primary Key Convention which states:

Code First infers that a property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column.

In your case you have in fact taken advantage of this conventions, so your code would probably work appropriately even without the [Key] attribute if your ID property would have been public.

Outras dicas

You should tell which value is your key to entity framework.

public class TestPerson
{
    [Key] public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Hair { get; set; }
    public string Race { get; set; }
    public string Measurements { get; set; }
}

public class TestPersonContext : DbContext
{
    public DbSet<TestPerson> TestPersons { get; set; }
}

You may read more about DataAnnotations from http://msdn.microsoft.com/en-us/data/jj591583.aspx

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top