When dealing with "EF-Code First," how can I define Keys?

asp.net c#-4.0 code-first entity-framework


When using "EF-Code First," I get a ModelValidationException (at the bottom). It asks me to define a Key, but I'm not really clear what that entails.

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)

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

        Console.WriteLine(o.Count()); // This line throws!

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.

11/8/2012 10:53:46 AM

Accepted Answer

For all the fields that you want EF to generate database fields for, you must utilize properties rather than private local variables.

Get; Set; Public Guid Id

1/5/2011 10:24:24 AM

Popular Answer

Create attributes for your fields, and then utilize the[Key] feature similar to this:

public Guid MyId { get; set; }

To get the KeyAttribute, you must import and reference System.ComponentModel.DataAnnotations.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow