How to determine the keys when working with "EF-Code First"?

I get a ModelValidationException (below) when working with "EF-Code First". He wants me to define the Key, but I'm not sure what exactly this 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' does not have a key. Define a key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: EntitySet units are based on the Unit type, which does not have specific keys.

+5
source share
3 answers

, , EF .

Public Guid Id {get; ;}

+3

, [Key] :

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

System.ComponentModel.DataAnnotations, KeyAttribute. .

+8

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

0
source

All Articles