【问题标题】:Entity Framework Core still picks up old columnEntity Framework Core 仍然选择旧列
【发布时间】:2018-01-22 22:18:24
【问题描述】:

我最近从表中删除了 ConversationId 列。当我开始调试我的服务并尝试保存时,我收到了一个错误:

列名“ConversationId”无效。

代码:

public class AstootContext : DbContext
{
    public AstootContext(DbContextOptions<AstootContext> options)
        : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }

    public DbSet<ServiceRequest> ServiceRequests { get; set; }
}

我的实体看起来像这样:

public class ServiceRequest
{
    public int Id { get; set; }
    public int SenderUserId { get; set; }
    public int PriceTypeId { get; set; }
    public decimal Price { get; set; }
    public bool IsAccepted { get; set; }
    public DateTime Created { get; set; }
    public int MessageId { get; set; }
}

所有对ConversationId 的引用均已从代码中删除,我已重新构建,但仍然出现此错误,我不明白为什么。

这是我的 SQL Server 表,您可以看到没有ConversationId

是否有我需要删除的秘密缓存或我必须运行的东西来更新它?

【问题讨论】:

  • 我想你可以尝试再次运行migrations 来更新修改后的列
  • @HaHoang 我目前没有使用迁移,我的数据库没有反映我的外键结构
  • 听起来你有一个名为 Conversation 的实体,它拥有像 public ICollection&lt;ServiceRequest&gt; ServiceRequests { get; set; } 这样的集合导航属性,不是吗?
  • 一旦你有了你的模型(来自现有数据库),你应该使用迁移来保持数据库与模型的任何更改同步。
  • @IvanStoev 就是这样,谢谢。如果您将其发布为答案,我会将其标记为正确

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

EF Core 是基于代码的 ORM,这里最重要的是 M - Mapper。实际的数据库结构是什么并不重要,重要的是 EF *认为**它基于您的代码模型(实体类及其属性,结合数据注释、流畅的配置和一组约定)。

所以问题应该源于代码。由于您已经删除了 explicit 属性,它应该是由shadow property 引起的。正如文档链接中所解释的,shadow 属性通常是按照惯例从关系中引入的:

当发现关系但在依赖实体类中没有找到外键属性时,可以按照约定创建影子属性。在这种情况下,将引入影子外键属性。

文档还解释了在不同场景中应用的命名规则。

可以通过多种方式引入名为ConversationId 的影子属性,但根据提供的信息,最可能的原因是有一个名为Conversation 的实体类与ServiceRequest 定义了一对多关系通过拥有一个集合类型的导航属性:

public class Conversation
{
    public int Id { get; set; }
    // ...
    public ICollection<ServiceRequest> ServiceRequests { get; set; }
}

根据你的评论确实是这样。

为了完整起见,以下是生成此类属性的其他一些可能场景:

(1)Conversation中没有集合导航属性,引用ServiceRequest中的导航属性:

public class Conversation
{
    public int Id { get; set; }
    // ...
}

public class ServiceRequest
{
    // ...
    public Conversation Conversation { get; set; }
}

(2)ConversationServiceRequest中没有导航属性,流畅配置:

modelBuilder.Entity<Conversation>()
    .HasMany<ServiceRequest>();

modelBuilder.Entity<ServiceRequest>()
    .HasOne<Conversation>();

或以上的变体。

(3) 不涉及关系,通过fluent配置创建影子属性:

modelBuilder.Entity<ServiceRequest>()
    .Property<int>("ConversationId");

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-22
    • 2022-11-13
    相关资源
    最近更新 更多