[英]Migrating form Navigation Property to Foreign Key in Entity Framework
我目前有一个正确的导航EF实体,如:
public class Person
{
public int Id { get;set;};
public string Name { get;set;};
public virtual Office WorkingAt { get;set;}
}
public class Office
{
public int Id {get;set;}
public string Name { get;set;}
public string Address {get;set;}
}
我想从使用WorkingAt
的“导航属性”更改为对Office
对象的Id的简单引用。
我该怎么做呢? 我不清楚迁移路径应该是什么。
我的数据库中已有数据, Person
表包含一个我想继续使用的Office_Id
列。
正如此处与Entity Framework Code First所讨论的那样,您需要至少有一个导航属性才能使您的关系正常工作。
但是,如果您想保留导航属性(为了避免处理迁移)并且只是向模型添加外键,那么您可以使用ForeignKey DataAnnotation来实现。 这样您就明确告诉Entity Framework您的意图。
public class Person
{
public int Id { get;set;}
public string Name { get;set;}
[ForeignKey("Office")]
public int OfficeId { get; set; }
public virtual Office WorkingAt { get;set;}
}
可以实现此目的的另一种方法是将ForeignKey注释添加到navigation属性并告知哪个属性将充当外键:
public class Person
{
public int Id { get;set;}
public string Name { get;set;}
public int OfficeId { get; set; }
[ForeignKey("OfficeId")]
public virtual Office WorkingAt { get;set;}
}
您不需要将该字段表示为代码中的外键。 由于您没有导航属性,因此就EF而言,它只是Person
表上的一列。 您没有使用导航属性,无论它是否与外键无关,因为您无法再使用它来自动加入Office
表。
由于它已经将Office_Id
用作数据库中的外键,因此您只需执行以下操作:
public class Person
{
public int Id { get;set;}
public string Name { get;set;}
public int Office_Id { get; set; }
}
然后运行Add-Migration
。 它可能会尝试删除Up
方法中的外键(并将其添加回Down
方法)。 使用外键删除这两行。 理想情况下,您的Up
和Down
方法应为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.