实体框架在生成数据库时创建下划线列 [英] Entity Framework creates underscore column when generating database

查看:78
本文介绍了实体框架在生成数据库时创建下划线列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的对象模型,如下所示...

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

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

使用EntityFramework生成基础数据库将导致以下模式...

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

产品


  • ProductId

  • CategoryId

  • Category_CategoryId

类别


  • CategoryId

> Products 表中, CategoryId 列始终设置为0,而 Category_CategoryId 列包含产品所属类别的ID。

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.

如何在 CategoryId 列中设置类别ID,并防止生成 Category_CategoryId 列?

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

推荐答案

应用 C的ForeignKey 属性ategory CategoryId 属性。然后更改 CategoryId 属性类型以匹配 Category 类的 CategoryId (都应为long或int)。

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


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

这篇关于实体框架在生成数据库时创建下划线列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆