Entity Framework creates underscore column when generating database

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-12 18:49:25

问题


I have a simple object model as follows...

public class Product
{
    public long ProductId { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

and

public class Category
{
    public long CategoryId { get; set; }
    public List<Product> Products { get; set; }
}

Generating the underlying database with EntityFramework results in the following schema...

Products

  • ProductId
  • CategoryId
  • Category_CategoryId

Categories

  • CategoryId

In the Products table, the CategoryId column is always set to 0 while the Category_CategoryId column contains the id of the category the product belongs to.

How do I cause the category id to be set in the CategoryId column and prevent the Category_CategoryId column from being generated?


回答1:


Apply ForeignKey attribute to Category OR CategoryId property. And change CategoryId property type to match CategoryId of Category class (both should be long or int).

public class Product
{
    public long ProductId { get; set; }
    public long CategoryId { get; set; }
    [ForeignKey("CategoryId")]
    public Category Category { get; set; }
}

public class Category
{
    public long CategoryId { get; set; }
    public List<Product> Products { get; set; }
}

OR

public class Product
{
    public long ProductId { get; set; }
    [ForeignKey("Category")]
    public long CategoryId { get; set; }
    public Category Category { get; set; }
}

You can do same via fluent mapping:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .HasRequired(p => p.Category)
        .WithMany(c => c.Products)
        .HasForeignKey(p => p.CategoryId)
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}


来源:https://stackoverflow.com/questions/14729294/entity-framework-creates-underscore-column-when-generating-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!