EF Code First 5.0.rc 迁移不会更新 Identity 属性

2024-03-06

假设我们正在使用 EF Code First,我们有这个简单的模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace EFCodeFirstIdentityProblem.Models
{
    public class CAddress
    {
        public int ID { get; set; }

        public string Street { get; set; }
        public string Building { get; set; }

        public virtual CUser User { get; set; }
    }

    public class CUser
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public string Age { get; set; }

        [Required]
        public virtual CAddress Address { get; set; }
    }

    public class MyContext : DbContext
    {
        public DbSet<CAddress> Addresses { get; set; }
        public DbSet<CUser> Users { get; set; }
    }
}


像这样,CAddress将会主要的结束这种 1:0..1 的关系。 接下来我们将连接字符串添加到Web.Config(我使用MSSQL 2008 R2),制作一个使用该模型的控制器,运行。 EF Code First 按预期为我们创建了表:

所以,假设我们犯了一个错误,事实上我们想要CUser to be 主要的这种 0..1:1 关系的结束。所以我们做出改变:

        ...
        [Required]
        public virtual CUser User { get; set; }
        ...

        ...
        public virtual CAddress Address { get; set; }
        ...

构建,然后在包管理器控制台中运行并添加一些迁移:

PM> Enable-Migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201208021053489_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project EFCodeFirstIdentityProblem.
PM> Add-Migration ChangeDependency
Scaffolding migration 'ChangeDependency'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201208021157341_ChangeDependency' again.
PM> 

以下是我们为“ChangeDependency”迁移提供的内容:

namespace EFCodeFirstIdentityProblem.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ChangeDependency : DbMigration
    {
        public override void Up()
        {
            DropForeignKey("dbo.CUsers", "ID", "dbo.CAddresses");
            DropIndex("dbo.CUsers", new[] { "ID" });
            AlterColumn("dbo.CAddresses", "ID", c => c.Int(nullable: false));
            AlterColumn("dbo.CUsers", "ID", c => c.Int(nullable: false, identity: true)); //identity: true - this is important
            AddForeignKey("dbo.CAddresses", "ID", "dbo.CUsers", "ID");
            CreateIndex("dbo.CAddresses", "ID");
        }

        public override void Down()
        {
            DropIndex("dbo.CAddresses", new[] { "ID" });
            DropForeignKey("dbo.CAddresses", "ID", "dbo.CUsers");
            AlterColumn("dbo.CUsers", "ID", c => c.Int(nullable: false));
            AlterColumn("dbo.CAddresses", "ID", c => c.Int(nullable: false, identity: true));
            CreateIndex("dbo.CUsers", "ID");
            AddForeignKey("dbo.CUsers", "ID", "dbo.CAddresses", "ID");
        }
    }
}

重要的部分是:

AlterColumn("dbo.CUsers", "ID", c => c.Int(nullable: false,身份:真实));

因此,CUsers.ID 现在必须成为数据库中的身份。让我们将这些更改提交到数据库:

PM> 
PM> Update-Database -Verbose
Using StartUp project 'EFCodeFirstIdentityProblem'.
Using NuGet project 'EFCodeFirstIdentityProblem'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'EFTest' (DataSource: (local), Provider: System.Data.SqlClient, Origin: Configuration).
Applying code-based migrations: [201208021157341_ChangeDependency].
Applying code-based migration: 201208021157341_ChangeDependency.
ALTER TABLE [dbo].[CUsers] DROP CONSTRAINT [FK_dbo.CUsers_dbo.CAddresses_ID]
DROP INDEX [IX_ID] ON [dbo].[CUsers]
ALTER TABLE [dbo].[CAddresses] ALTER COLUMN [ID] [int] NOT NULL
ALTER TABLE [dbo].[CUsers] ALTER COLUMN [ID] [int] NOT NULL
ALTER TABLE [dbo].[CAddresses] ADD CONSTRAINT [FK_dbo.CAddresses_dbo.CUsers_ID] FOREIGN KEY ([ID]) REFERENCES [dbo].[CUsers] ([ID])
CREATE INDEX [IX_ID] ON [dbo].[CAddresses]([ID])
[Inserting migration history record]
Running Seed method.
PM> 

CUsers.ID 的迁移没有给出 SQL 指令,成为数据库中的标识列。所以,正因为如此,就有一个问题:

(updated database) enter image description here enter image description here

因此,用户现在是主体端,并且必须具有 ID Identity:“YES”标志,但 Identity 仍然是“NO”。地址是从属端,必须具有 ID 身份“NO”,但仍然是“YES”。所以我无法将新用户添加到用户表中,因为不会为新实例生成新ID。

如果我删除整个数据库,EF Code First 会正确地从头开始创建新表,因此这只是迁移的问题。

在这种情况下我该怎么办?这是 EF 迁移错误吗?


我不确定这是否是一个错误,因为还有另一个问题 - 你无法更改现有列以标识或删除标识 http://blog.sqlauthority.com/2009/05/03/sql-server-add-or-remove-identity-property-on-column/。我可以想象这被认为是完全手动迁移,以明确您必须移动数据。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

EF Code First 5.0.rc 迁移不会更新 Identity 属性 的相关文章

  • LINQ 到实体日期时间比较

    我在将 LINQ 中的日期与实体表达式进行比较时遇到问题 我想检查一下是否DateTime DateTime whole day 我想这样做 return context Events Any x gt x UserId id x Date
  • VS2012 中的实体框架问题 - 重命名属性不粘

    我试图在 VS2012 中创建一个新项目 其中包含管理 MVC4 项目 网站 MVC4 项目和通用实体框架 dll 项目 我使用了现有的数据库并从中生成了我的实体 我更新了一些关系属性的名称并保存 然后 我将对实体框架项目的引用添加到我的两
  • 使用 List.Contains 方法为 LINQ 构建表达式树

    Problem 我正在重构一些LINQ查询我们的 Web 应用程序中的多个报告 并且我尝试将一些重复的查询谓词移至它们自己的中IQueryable扩展方法 以便我们可以将它们重新用于这些报告以及将来的报告 正如您可能推断的那样 我已经重构了
  • 升级到 Visual Studio 16.3.0 后,dotnet ef 命令不再起作用

    这种情况首先发生在家里 所以我想这可能是我家里的台式电脑的问题 但现在我回到工作岗位 我尝试升级并得到了同样的结果 升级前截图 升级 Visual Studio 后的屏幕截图 我得到的错误是 无法执行 因为找不到指定的命令或文件 造成这种情
  • 将许多表转换为 Excel 列

    我创建了用于文章审阅的网络应用程序 我有一个名为 Article 的表 每个表Article有一些ArticleReview Article ArticleId ArticleTitle NumberOfComment NumberOfVi
  • 如何重用具有稍微不同的 ProcessStartInfo 实例的 Process 实例?

    我有以下开始的代码robocopy https technet microsoft com en us library cc733145 aspx as a Process 我还需要进行数据库查询以确定每次需要复制哪些目录robocopy被
  • 如何让实体框架初始化新创建的实体上的集合?

    我正在尝试用一些测试数据来种子我的数据库IDatabaseIntialiser像这样 protected override void Seed BlogDataContext context
  • EF - 从自动迁移转向手动迁移

    结束了漫长的一天测试各种场景 我不必重新创建生产数据库 我们从 EF 开始 在开发过程中没有足够明智地从自动迁移转向命名迁移 现在 我正在尝试倒带时钟 并创建与生产数据库一致的初始迁移 是否可以将模型与迁移表中的自动迁移进行对齐 我应该创建
  • 使用 DbMigrationsConfiguration 将ExecutionStrategy 设置为 SqlAzureExecutionStrategy?

    我今天看到一篇关于实现 SqlAzureExecutionStrategy 的帖子 http romiller com tag sqlazureexecutionstrategy http romiller com tag sqlazure
  • 使用经度和纬度查找给定距离内的所有附近客户

    我有一个包含客户经度和纬度的数据库 我有一个搜索表单 用户将在其中输入日志 纬度 距离下拉列表包含 50 英里 100 英里 当用户单击搜索时 我想编写一个 linq 查询从数据库中获取此距离半径内的所有客户 如何使用 C 和 linq 来
  • 实体框架、dll、excel

    我用C 编写了Excel使用的dll 该dll是COM注册的 我与 Excel 的连接没有问题 该 dll 使用实体框架 5 从 SQL Server 数据库检索数据 如果我通过控制台应用程序运行该 dll 则该 dll 工作正常 但是当我
  • 学习实体框架[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Web API 的 ASP.NET MVC Core 控制器 PATCH 方法

    给定一个数据库表 Person 包含 3 列 Id 名字和姓氏 使用真实的 DbContext 时 ASP NET Core Web API MVC 控制器方法 PATCH 仅修改姓氏 看起来如何 我根本不知道如何实现它 并且找不到相关教程
  • 在 IDbCommandInterceptor 中捕获调用方法名称

    我在用IDbCommandInterceptor捕获实体框架查询 这样我就可以访问一些重要信息 例如DbParameters and DbCommand etc 我还需要获取调用此查询的位置 我试图通过使用来得到这个StackTrace S
  • EF6 Code First 支持表值函数吗?

    是否可以在 EF6 Code First 中调用 TVF 我首先使用 EF6 数据库启动了一个新项目 EF 能够将 TVF 导入到模型中并调用它就好了 但是 对于我一直在处理的没有 RI 的大型只读数据库 更新模型变得非常耗时并且存在问题
  • C# 中 LINQ 中的按多列分组

    我有一个类如下 public class ActualClass public string BookName get set public string IssuerName get set public DateTime DateOfI
  • 我的 SQL 表设置为允许该列为 NULL,但是当我运行它时,它说它不能为 NULL。什么/为什么/如何?

    所以我在这里遇到了很奇怪的困境 我的 SQL 表设置为允许 ZipCode 列为空 如下所示 CREATE TABLE dbo Companies CompanyId BIGINT IDENTITY 1 1 NOT NULL PRIMARY
  • 实体框架服务层更新 POCO

    我正在使用Service Layer gt Repository gt Entity Framework Code First w POCO objects方法 我在更新实体方面遇到了困难 我正在使用 AutoMapper 将域对象映射到视
  • 选择里面的 Include in EF Core

    我有一个如下所示的实体 为简洁起见 部分删除 它包括许多其他属性 public class Tender Key DatabaseGenerated DatabaseGeneratedOption Identity public int I
  • 使用 EF6 连接到 SQL Server

    在 EF5 之前 为了连接到 SQL Server 2012 我所需要做的就是指定一个如下所示的连接字符串 Data Source SqlExpress Initial Catalog MyDatabase Integrated secur

随机推荐