我有一个场景,我需要使用 Entity Framework 4.1 Code-First 将一个类的两个属性绑定到另一个类。(作为参考,Upshot.js 正在使用此模型以在使用 Knockout.js 2.1 的单页应用程序中使用)
通常,我会执行以下操作:
public class Person
{
[Key]
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
public Address OfficeAddress { get; set; }
}
public class Address
{
[Key]
public int AddressId { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
这允许 HomeAddress 和 OfficeAddress 都引用 Address 类的实例。
请注意,这不是我的真实数据模型。它仅用于说明目的。在现实生活中,我可能会使用 ICollection。不幸的是,对于这种特殊情况是不可行的,我确实需要维护从一个类到另一个类的多个引用。
In this particular scenario, it is also possible for a person to exist without any addresses defined. It is also possible for addresses to exist without a person. (As mentioned, this data model is just an example.)
While this compiles correctly, and I can even create and save data, upshot complains bitterly when it attempted to use this model.
It gives an (inner) exception like the following:
{"Unable to retrieve association information for association 'KnockoutTest.Models.Person_HomeAddress'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information."}
So... I attempted to set the Foreign Key information on the DbContext class like
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(m => m.HomeAddress);
modelBuilder.Entity<Person>()
.HasOptional(m => m.OfficeAddress);
}
No joy! This still gave me the same exception.
I am not sure how to set up the foreign key association so that multiple properties on one class can reference another class--at least not in a way that upshot will be pleased and stop complaining for a while.
What am I doing wrong, and how do I fix it?