简体   繁体   English

使用具有自动迁移实体框架的新表添加外键mvc c#

[英]Adding foreign key with new table with automatic migrations entity framework mvc c#

I would like to add a new table and a foreign key of an existing table in SQL Server with code first automatic migrations. 我想在SQL Server中添加一个新表和一个现有表的外键,首先是代码自动迁移。 The only problem I have is that there is data in the table and I can't set the foreign key to a default value for existing data. 我唯一的问题是表中有数据,我无法将外键设置为现有数据的默认值。

Exemple : 例如:

Cars table 汽车表

Name Color 名称 颜色
Matrix Blue 矩阵
Camry Red 凯美瑞

Now I want to add the Brand table : 现在我要添加Brand表:

Cars table 汽车表

Id Name Color BrandId Id 名称 颜色 BrandId
1 Matrix Blue 1 1 矩阵 1
2 Camry Red 1 2 凯美瑞 1

Brand table 品牌表

Id Name 身份 名称
1 Toyota 1 丰田

The question is : How can I set the default BrandId to 1 in my Model Car without having a foreign key constraint error when I run Update-Database command? 问题是:当我运行Update-Database命令时,如何在没有外键约束错误的情况下将模型车中的默认BrandId设置为1?

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Cars_dbo.Brands_BrandId". The conflict occurred in database "Example", table "dbo.Brands", column 'Id'.

For now, In my Configuration.cs file, I add my car brands like this : 现在,在我的Configuration.cs文件中,我添加了这样的汽车品牌:

context.Brands.AddOrUpdate(
                new Brand{ Id = 1, Name = "Toyota" }
           );

In My context, I override protected override void OnModelCreating ( DbModelBuilder modelBuilder ) and apply this relation : 在我的上下文中,我覆盖受保护的覆盖void OnModelCreating(DbModelBuilder modelBuilder)并应用此关系:

modelBuilder.Entity<Car>().HasRequired<Brand>(t => t.Brand);

In my Car model : 在我的车型:

[Required( ErrorMessage = "The brand is mandatory" )]
public int BrandId { get; set; }
[ForeignKey( "BrandId" )]
public virtual Brand Brand { get; set; }

In the constructor of the Car model, I set the default value to the BrandId : 在Car模型的构造函数中,我将默认值设置为BrandId:

public Car() 
{
    BrandId = 1;
}

"Automatic migration" in EF is a bit of an ambiguous term but if you mean the one which attempts to modify your db for you, you can't. EF中的“自动迁移”是一个含糊不清的术语,但如果你的意思是那个试图为你修改数据库的那个,你就不能。 You have to use the form of migrations** where you are running Add-Migration from the visual studio console to generate migration classes. 您必须使用迁移形式**从Visual Studio控制台运行Add-Migration以生成迁移类。 This is generally a much much better way of handling migrations anyway. 这通常是无论如何处理迁移更更好的方法。

For this, I would I would typically use the Sql function to disable constraint checking. 为此,我通常会使用Sql函数来禁用约束检查。

Sql("ALTER TABLE Cars NOCHECK CONSTRAINT ALL")

add the FK, do some logic to populate that column, and then enable constraint checking again. 添加FK,执行一些逻辑来填充该列,然后再次启用约束检查。

Sql("ALTER TABLE Cars CHECK CONSTRAINT ALL")

Another possibility, is maybe the cars already in the system you want to have null brands, but any future cars would have to reference an existing brand. 另一种可能性是,您可能已经在系统中拥有null品牌的汽车,但任何未来的汽车都必须参考现有品牌。 In that case you allow NULL in that column, and handle the validation requirement in code. 在这种情况下,您在该列中允许NULL ,并在代码中处理验证要求。

In fact you should always handle all validation in code, never rely on your database to do validation for you. 实际上,您应该始终处理代码中的所有验证,而不是依靠您的数据库为您进行验证。


** These are still occasionally referred to as Automatic Migrations since typically you set them to be applied automatically when your application runs. **这些仍然有时被称为自动迁移,因为通常将它们设置为在应用程序运行时自动应用。

I had this problem too, and I found a way to solve this problem. 我也有这个问题,我找到了解决这个问题的方法。

first, you should define only public int BrandId { get; set; } 首先,你应该只定义public int BrandId { get; set; } public int BrandId { get; set; } public int BrandId { get; set; } and run your project with that. public int BrandId { get; set; }并运行你的项目。 then, in your database give a valid value (a primary key for your foreign key) to BrandId . 然后,在您的数据库中为BrandId提供有效值(外键的主键)。 Now, you can define public virtual Brand Brand { get; set; } 现在,您可以定义public virtual Brand Brand { get; set; } public virtual Brand Brand { get; set; } public virtual Brand Brand { get; set; } , run your project again and you won't get no more errors. public virtual Brand Brand { get; set; } ,再次运行你的项目,你不会再得到错误。

Maybe it's not be the best solution for this problem, but if you've had some primary key for your foreign key , you can use this way. 也许它不是解决这个问题的最佳解决方案,但是如果你的外键有一些主键,你可以用这种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用codefirst迁移实体框架6向模型和新模型添加外键 - Adding a foreign key to the model and a new model using codefirst migrations entity framework 6 在带有外行键字段的代码优先迁移的Entity Framework 7中添加索引 - Adding an Index in Entity Framework 7 with Code First Migrations on a field that is a Foreign Key C#Entity Framework:使用自动迁移重命名表字段而不丢失数据 - C# Entity Framework : Rename table field without losing data, using automatic migrations 我应该将外键表存储为Entity Framework中的外键ID还是该表的C#模型? - Should I store foreign key table as foreign key ID or the C# model of that table in Entity Framework? C#实体框架中的外键 - Foreign Key in Entity Framework in C# 外键实体框架-代码优先迁移 - Foreign key Entity Framework - code first migrations C# Entity Framework Migrations 向字符串添加奇怪的字符 - C# Entity Framework Migrations adding weird characters to string 实体框架6添加外键 - Entity Framework 6 Adding foreign key 实体框架自动外键人口 - Entity Framework automatic foreign key population 在实体框架中添加新记录时不会自动设置外键 - Foreign key is not setting automatically while adding new record in entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM