2012-02-25 33 views
0

不知道我是否正確地問這個問題(我是EF新手)。將我的實體框架列表視爲poco列表

基本上這是我的問題。我有一個名爲城市類,這是一個非常簡單的類,但它在我的數據庫表究竟

public class City 
{ 
    public int Id { get; set; } 
    public string Country { get; set; } 
    public string Province { get; set; } 
    public string CityName { get; set; } 

    public City() 
{ 
    // TODO: Add constructor logic here 
} 
} 

地圖現在在我的系統後,我有一個城市列表 公開名單的城市{獲得;私人設置; }

和LINQ查詢這樣

using (MYdbEntities myentity = new MYdbEntities()) 
     { 
      var efCities = (from c in myentity.Cities 
         orderby c.CityName 
         select c);   
      Cities = efCities.ToList(); //this line croaks   
     } 

,所以我得到的問題是,LINQ返回從模型實體的名單,而城市是城市對象的列表是不同的。 但我怎麼能投efCities到城市(短做我自己的映射BLECH一個可怕的循環)

我谷歌廣告獲得奇怪的東西約T4模板生成一些東西 請啞下來我:)

我想保持我的城市對象儘可能簡單而不實體框架的任何知識,因爲我打算如果我理解你的權利在其他地方使用它

感謝

+0

您是否使用EF代碼優先(> 4.1)? – 2012-02-25 16:14:25

回答

1

,你們的城市類(模型)是不與EF創建的相同,但具有相同的特性。

根據你所擁有的最簡單的方法是

var myCities = (efCities.Select(o=> new City() { 
    Id = o.Id, 
    Country = o.Country 
    .... 
}).ToList(); 

請原諒格式化,很難在iPad上。

基本上你正在做的是創建你的城市類的新列表,在Select函數中映射每個屬性。

您也可以使用類似AutoMapper的東西來自動地映射/填充城市類。您可以在這裏找到AutoMapper http://automapper.codeplex.com/

希望幫助

山姆

+0

嗯,我想我明白,但不知道新的MyCities()來自哪裏 – Crudler 2012-02-25 16:57:54

+0

是的,對不起,由於某種原因,我認爲你的城市類被命名(貧窮)的城市,並試圖區分。我已編輯答案:) – sambomartin 2012-02-25 19:31:46

+0

謝謝。像炸彈一樣工作。仍然是新的C#所以不知道我可以映射類似的字段使用=>真正強大的 – Crudler 2012-02-26 07:37:50

0

你可以寫一個擴展方法CopyTo源對象的屬性複製到destionation對象(有相同的名字)。你select c將是現在select c.CopyTo<City>()

例子:

public class City1 
{ 
    public int Id { get; set; } 
    public string Country { get; set; } 
    public string Province { get; set; } 
    public string CityName { get; set; } 
} 

public class City2 
{ 
    public int Id { get; set; } 
    public string Country { get; set; } 
    public string Province { get; set; } 
    public string CityName { get; set; } 
} 

City2 c2 = new City2(); 
new City1() { 
     Id = 3, Country = "aaa", Province = "bbb", CityName = "ccc" } 
.Copy(c2); 

//or 

City2 c2 = new City1() { 
      Id = 3, Country = "aaa", Province = "bbb", CityName = "ccc" } 
      .Copy<City2>(); 

public static class MyExtensions 
{ 
    public static void CopyTo(this object src, object to) 
    { 
     Type dstType = to.GetType(); 
     foreach (var prop in src.GetType() 
           .GetProperties() 
           .Select(pi => new { Name = pi.Name, Value = pi.GetValue(src, null) })) 
     { 
      dstType.GetProperty(prop.Name).SetValue(to, prop.Value, null); 
     } 
    } 

    public static T CopyTo<T>(this object src) 
    { 
     Type dstType = typeof(T); 
     T to = (T)Activator.CreateInstance(dstType); 
     CopyTo(src, to); 
     return to; 
    } 
}