0

我需要使用一对多关系播种我的数据(一个联系人可以有多个地址)但它不会让我播种我指定为 ICollection 的地址。我不能将它存储为字符串或整数。那我该怎么办?

 namespace SuccessEd.Data.Model
{
    public class Contact
    {
        public int ContactId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
    }
}




 namespace SuccessEd.Data.Model
{
    public class Address
    {
        public int AddressId { get; set; }

        public string HomeAddress { get; set; }
        public string BusinessAddress { get; set; }
        public string PoBox { get; set; }

        public int ContactId { get; set; }
        public virtual Contact Contact { get; set; }

    }
4

3 回答 3

2

我建议使用称为 Fluent API 的东西。您可以在此处阅读有关 Fluent api 的更多信息

为了让事情更容易,你可以看看这个方法:我对你的类做了一些改变

namespace SuccessEd.Data.Model
{
    public class Contact
    {        
        public Contact () 
        {
            AddressList = new List<Address>();
        }

        public int ContactId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
   }
}

和另一个

namespace SuccessEd.Data.Model
{
    public class Address
    {
        public Adress() {}

        public int AddressId { get; set; }

        public string HomeAddress { get; set; }
        public string BusinessAddress { get; set; }
        public string PoBox { get; set; }

        public virtual Contact Contact { get; set; }
    }
}

请记住,您的课程必须是公开的。两个都!!

在您的 OnModelCrating 上。有了这个,你必须给用户一个地址

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Contact>().HasRequired<Address>(s => s.AddressId).WithMany(s => s.AddressList).HasForeignKey(s => s.ContactId);
}

我希望这能帮助你解决你的问题。

干杯

于 2013-10-26T17:25:05.370 回答
2

我认为你在正确的轨道上。尽管我不认为地址需要是虚拟的。如果您正在使用数据库,最好添加一个名为contact id 的属性并将其提供给contact 和adress。

于 2013-10-26T17:13:40.863 回答
1

您在正确的轨道上,除了您需要使用 ICollection<> 而不是 List<> 来获取 Contact 类中的地址。像这样:

public virtual ICollection<Address> Addresses { get; set; }

检查一下为什么: 为什么在多对多/一对多关系上使用 ICollection 而不是 IEnumerable 或 List<T>?

MSDN 上的更多解释:http: //msdn.microsoft.com/en-us/data/jj591620.aspx#UniDirectional

于 2013-10-26T17:20:10.333 回答