entity-framework - Entity Framework 代码首先添加不需要的外键列

标签 entity-framework code-first

我在类别新闻之间存在多对一关系。

我遇到的问题是 EF 一直在我的表中添加一个我不想要的外键列!

新闻类

public class News
{
    public News()
    {

    }

    [Key]
    public int NewsID { get; set; }

    public int PublishedByID { get; set; }
    public string PublishedByFullName { get; set; }
    public string PublishedByEmail { get; set; }
    public DateTime DatePublished { get; set; }
    public string Title { get; set; }
    public string PreviewText { get; set; }

    public string BlobName { get; set; }

    public virtual Category Category { get; set; }
}

类别类

public class Category
{
    public Category()
    {
        News = new HashSet<News>();
    }

    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public string CategoryTypeName { get; set; }

    public virtual ICollection<News> News { get; set; }
}

数据库

Database

我的问题

如何删除 News 表中的 Category_CategoryID

我猜我在 OnModelCreating 方法中遗漏了一些代码。

最佳答案

需要在News类中添加id字段来引用Category。

public class News
{
    [Key]
    public int NewsID { get; set; }

    public int CategoryID { get; set; } // added

    public int PublishedByID { get; set; }
    public string PublishedByFullName { get; set; }
    public string PublishedByEmail { get; set; }
    public DateTime DatePublished { get; set; }
    public string Title { get; set; }
    public string PreviewText { get; set; }

    public string BlobName { get; set; }

    public virtual Category Category { get; set; }
}

关于entity-framework - Entity Framework 代码首先添加不需要的外键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31103482/

相关文章:

c# - Entity Framework 上的延迟加载与急切加载性能

database - 用代理单调递增的int作为PK创建数据库表是不是新趋势?

c# - 使用 Entity Framework 返回数据表

c# - Entity Framework 不将数据保存到 WPF 中的数据库

c# - EF Code First 约定允许 ICollection<T> 属性为空集合而不是 null?

c# - 实体代码优先用户、角色、用户角色表

c# - 如何删除 EF 代码优先数据库中的子一对多相关记录?

c# - EF6 : Foreign keys are not recognized on model generation for Sql Server DB

c# - 向 EF 实体添加非关系属性(连接操作)

c# - 首先编码与关系表中属性的多对多关系