我创建了所有模型,然后使用 Add-Migration Initial
添加了一个新的迁移。
添加迁移在迁移文件夹中创建了一个如预期的迁移文件,但由于某种原因,它创建了一个名为 client_id
的列两次。我希望创建一个名为 client_id
的列,其类型为整数且不可为 null。
我应该注意到 client_id
列引用了具有关系的 Clients
模型。
这是我的模型类的样子
[Table("scripter_campaigns")]
public class Campaign
{
[Key]
[Column(Order = 1)]
public int id { get; set; }
[Column(Order = 2)]
[StringLength(200)]
[Required]
[MinLength(5, ErrorMessage = "The title must be greater than 5 characters in length"),
MaxLength(200)]
public string name { get; set; }
[Column(Order = 3)]
[StringLength(200)]
public string layout { get; set; }
[Column(Order = 4)]
[StringLength(200)]
public string call_list_server_name { get; set; }
[Column(Order = 5)]
[StringLength(200)]
public string call_list_table_name { get; set; }
[StringLength(200)]
public string status { get; set; }
public string intro_url { get; set; }
public string use_transfer { get; set; }
public string route_callback_to { get; set; }
public string call_list_database_name { get; set; }
public int client_id { get; set; }
public DateTime? created_at { get; set; }
public DateTime? modified_at { get; set; }
public virtual Client Client { get; set; }
//Initilize the default value
public Campaign()
{
status = "Active";
use_transfer = "No";
route_callback_to = "Self";
}
}
但是它为迁移脚本中的 up() 方法生成了这段代码
CreateTable(
"dbo.scripter_campaigns",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 200),
layout = c.String(maxLength: 200),
call_list_server_name = c.String(maxLength: 200),
call_list_table_name = c.String(maxLength: 200),
status = c.String(maxLength: 200),
intro_url = c.String(),
use_transfer = c.String(),
route_callback_to = c.String(),
call_list_database_name = c.String(),
client_id = c.Int(nullable: false),
created_at = c.DateTime(),
modified_at = c.DateTime(),
Client_id = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.clients", t => t.Client_id)
.Index(t => t.Client_id);
我不明白 Client_id = c.Int()
是从哪里来的,但是当我尝试更新数据库时它给我带来了问题
这里是错误
Column names in each table must be unique. Column name 'Client_id' in table 'scripter_campaigns' is specified more than once.
此外,我是否需要数据库中的外键才能在我的对象之间建立关系?
最佳答案
Client_id = c.Int()
正在创建,因为 public virtual Client Client { get;放; }
这是因为你需要做以下事情
[ForeignKey("Client")]
public int client_id { get; set; }
当你的实体类中有以下内容时
public virtual Client Client { get; set; }
这样 [Table("scripter_campaigns")]
就会知道 client_id 的来源。
更新:[ForeignKey("Client")]
正在指示public int client_id { get;放; }
从 public virtual Client Client { get;放; }
对象。给出 scripter_campaigns
对象与 Client
对象相关。
关于c# - Add-Migration 一个列名被多次列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35210164/