EF中的(1到多个)级联实体

时间:2016-09-25 20:16:05

标签: c# entity-framework linq

我是一个完全的初学者,我有一个关于在EF中级联1到多个rel的小问题... 假设我有3个实体,一个国家有许多城市,每个城市都有很多酒店......

class Country 
{
    public int Id {get; set; }
    public string CountryName {get; set; }
    public virtual ICollection<City> Cityes {get; set; }  
}

class City 
{
   public int Id {get; set; }
   public string CityName {get; set; }
   public virtual Country Country {get; set; }
   public virtual ICollection<Hotel> Hotels {get; set; }
}

class Hotel 
{
   public int Id {get; set; }
   public string HotelName {get; set; }
   public virtual City City {get; set; }
}

这是我的简单存储库

public IQueryable<Hotel> GetAllHotels()
{
   return context.HotelTable.Include("City");
}

在我的MVC客户端中,我有一个简单的投影

public class HotelVm 
{
   public string HotelName  {get; set; }
   public string CityName {get; set; }
   public string CountryName {get; set; } // here is the problem
}

投影的工厂模型

public class Factory 
{
    public HotelVm Create(Hotel h)
    {
       return new HotelVm()
       {
          HotelName = h.HotelName , 
          CityName = h.City.CityName , 
          CountryName = ??? 
       }
    }
 }

最后我的MVC中的Controller

public Repository repo = new Repository();
public Factory fact = new Factory ();

public ActionResult Index()
{
    IQueryable<Hotel> hotel = repo.GetAllHotels();
    var result = hotel.ToList().Select(h=> fact.Create(h));
    return View(result);
}

现在很明显,我的创建HotelVM未将对象引用设置为对象的实例。 ...在我的创建新HotelVm ... 不确定如何在我的投影中得到国家的名称,或者我是否应该采取不同的策略...... 任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

修改存储库以加载City的相关实体。

public IQueryable<Hotel> GetAllHotels()
{
   return context.HotelTable.Include("City").Include("City.Country");
}

然后修改工厂以使用属于Country的{​​{1}}。

City

请务必使用防御性编码做法来防止例外public class Factory { public HotelVm Create(Hotel h) { return new HotelVm() { HotelName = h.HotelName, CityName = h.City.CityName, CountryName = h.City.Country.CountryName } } }

另请参阅:Loading Related Entities

相关问题