EF Code第一期NO KEY DEFINED

时间:2012-02-28 14:18:34

标签: entity-framework key poco code-first

使用POCO实体宽度EF

时出现以下错误
  

在模型生成期间检测到一个或多个验证错误:     System.Data.Edm.EdmEntityType :: EntityType'Brand'没有密钥   定义。定义此EntityType的键。     System.Data.Edm.EdmEntitySet:EntityType:EntitySet'Brand'基于   类型'品牌'没有定义键。

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);
        }
    }

数据库表

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

用途

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

如果[Key]注释与POCO一起使用来指示pk那么它工作正常但我不想在POCO中使用任何依赖类。

任何建议???

由于

1 个答案:

答案 0 :(得分:2)

您可以使用fluent API配置PK。您不必将数据库架构明确指定为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);
    }

您还可以在Country POCO上定义导航属性Brand

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; }
}

行动方法

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

        return View();
    }

然后在视图中

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