2013-10-26 23 views
0

我需要种子我的数据使用一对多的关系(一个联系人可以有很多地址)但它不会让我种子地址,我指定为ICollection。我不能将它存储为一个字符串或int。所以我该怎么办?如何种子Icollectable到数据库代码首先

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; } 

    } 
+0

你能准确地告诉我们什么不按预期工作吗? – Isantipov

+0

哦,我只是想知道我上面做了什么是正确的?自从我的教科书或互联网并没有真正告诉我如何做一对多的关系以后,我需要有人在写作方向上向我着色 – Pope43

+0

你有一个联系人列表,你想要一个函数来返回你的地址列表属于具有特定姓氏的联系人? – liran63

回答

2

我会建议使用一些所谓的流利的API。 You can read more about Fluent api here

,使事情变得简单,你可以看看这个方法:我做了一些更改类

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); 
} 

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

干杯

+0

teriible概述 –

+0

哈哈我还是比较新的这个网站。我总是使用标签并跳出盒子。这是我的第二天发表评论/答案所以是啊它应该会变得更好很快:) – photowalker

+0

嗯,我很欣赏我足够了解,知道你要去哪里以及你在做什么,所以我很欣赏这个例子 – Pope43

2

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

+0

所以我需要做的是添加contactId地址以及? – Pope43

+0

是的,并在您的查询中使用WHERE来获取这些地址。 – liran63

+0

是的,如果你正在使用数据库。或者,如果你需要检查哪个联系人附带一些地址 –

相关问题