gingerbreadboy
gingerbreadboy

Reputation: 7769

How do i define Keys when working with "EF-Code First"?

I get a ModelValidationException (at the bottom) when working with "EF-Code First". It wants me to define a Key but I'm not sure what exactly it means...

public class Unit
{
    Guid id;
    String public_id;
    String name;        
    bool deleted;
}

public class MyDataContext : DbContext
{
    public DbSet<Unit> Units { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Unit>().ToTable("sometable");
    }
}

[TestFixture]
public class DataTests
{
    [Test]
    public void Test()
    {
        MyDataContext database = new MyDataContext();
        var o = database.Units;


        Console.WriteLine(o.Count()); // This line throws!
        Assert.IsTrue(true);
    }
}

System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'Unit' has no key defined. Define the key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Units is based on type Unit that has no keys defined.

Upvotes: 5

Views: 6127

Answers (3)

Tim P.
Tim P.

Reputation: 2942

Make your fields properties, and then use the [Key] attribute like this:

[Key]
public Guid MyId { get; set; }

You will have to reference and import System.ComponentModel.DataAnnotations to get the KeyAttribute. More info can be found here.

Upvotes: 8

Murthy M
Murthy M

Reputation: 119

Without using [Key] if you use your column name as public Guid UnitID { get; set; } then EF considers this column as key column.

Upvotes: 0

James Harris
James Harris

Reputation: 1914

You need to use properties, not private local variables for all the fields that you want EF to create database fields for.

Public Guid Id {get; set;}

Upvotes: 3

Related Questions