Search code examples
entity-frameworkkeypococode-first

EF Code first issue NO KEY DEFINED


I am getting following error while using POCO entity width EF

One or more validation errors were detected during model generation: System.Data.Edm.EdmEntityType: : EntityType 'Brand' has no key defined. Define the key for this EntityType. System.Data.Edm.EdmEntitySet: EntityType: EntitySet 'Brand' is based on type 'Brand' that has no keys defined.

POCO

public class Brand
    {
         //[Key]
        public int BrandId { get; set; }
        public String BrandName { get; set; }
        public String CompanyName { get; set; }
        public Int32 CountryId { get; set; }
        public String Description { get; set; }
    }

DBConetxt

  public class DBContext : DbContext
    {
        public DBContext()
            : base("DBContext")
        { }


        public DbSet<Brand> Brand { get; set; }
        public DbSet<Country> Country { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Brand>().ToTable("dbo.Brand");
            modelBuilder.Entity<Country>().ToTable("dbo.Country");
            base.OnModelCreating(modelBuilder);
        }
    }

DB Table

BrandId int
BrandName   varchar
CompanyName varchar
CountryId   int
Description varchar
CreatedBy   int
CreatedDate datetime
ModifiedBy  int
ModifiedDate    datetime

uses

DBContext o = new DBContext();
return o.Brand.ToList();

If [Key] annotation is used with POCO to indicate pk then it works fine but I don't want to use any dependency class with POCO.

Any suggestions???

Thanks


Solution

  • You can configure the PK using the fluent API. You don't have to explicitly specify the database schema as dbo.

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Brand>().ToTable("Brand");
            modelBuilder.Entity<Brand>().HasKey(b => b.BrandId);
    
            modelBuilder.Entity<Country>().ToTable("Country");
            base.OnModelCreating(modelBuilder);
        }
    

    You can also define a navigational property Country on Brand POCO.

    public class Brand
    {
        public int BrandId { get; set; }
        public String BrandName { get; set; }
        public String CompanyName { get; set; }
        public Int32 CountryId { get; set; }
    
        public virtual Country Country {get; set; }
    
        public String Description { get; set; }
    }
    

    Action method

        public ActionResult Create()
        {
            ViewData["Countries"] = new SelectList(db.Country.ToList(), 
                   "CountryId", "CountryName");
    
            return View();
        }
    

    Then in view

    @Html.DropDownListFor(model => model.CountryId, 
              (IEnumerable<SelectListItem>)ViewData["Countries"], "-")