且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该如何声明外键关系,使用code首先实体框架(4.1)在MVC3?

更新时间:2022-11-04 19:02:00

如果你有一个订单类,添加引用模型中的另一个类的属性,例如客户应该足以让EF知道有在那里的关系:

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

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

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

您可以随时将 FK 关系明确:

You can always set the FK relation explicitly:

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

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

ForeignKeyAttribute 构造函数的字符串作为参数:如果你将它放在它重新presents关联的导航属性的名称外键属性。如果你把它放在导航属性将其重新presents相关联的外键的名称。

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

这句话的意思是,如果你在哪里放置 ForeignKeyAttribute 客户属性,该属性将采取客户ID 在构造函数中:

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }


基于编辑的最新code
你得到,因为这行的错误:


EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF会寻找一个名为来使用它作为外键执法财产。你可以做两件事情:

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1)删除 ForeignKeyAttribute 并把它替换了 RequiredAttribute标签标记为需要的关系:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

装饰用 RequiredAttribute标签也有一个很好的副作用的属性:在数据库中的关系与创建ON D​​ELETE CASCADE

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

我也建议让物业虚拟启用延迟加载。

I would also recommend making the property virtual to enable Lazy Loading.

2)创建一个名为属性,将作为一个外键。在这种情况下,它可能更有意义叫它例如 PARENTID (你需要在 ForeignKeyAttribute $ C $改名字C>以及):

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

在我在这种情况下,尽管它工作得更好有它周围的其他方式的经验:

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }