0

有無論如何在實體框架中創建自動投影嗎?看到請:實體框架中的自動投影

public class Person{ 
    public int Id {get; set;} 
    public string FirstName {get; set;} 
    public string LastName {get; set;} 
    public string FatherName {get; set;} 
    public string City {get; set;} 
    public string AddressLine {get; set;} 
    public string Something {get; set;} 
} 

public class PersonNameModel{ 
    public string FirstName {get; set;} 
    public string LastName {get; set;} 
    public string FatherName {get; set;} 
} 

public class PersonAddressModel{ 
    public string City {get; set;} 
    public string AddressLine {get; set;} 
} 

// etc... 

我的意思是我能夠代替正常的投影像:

context.Persons.Select(t => new PersonNameModel{ FirstName = t.FirstName /* etc */ }); 

白衣,可以使用反射和創建一個自動投影,類似的擴展方法:

public static class MyExtensions{ 
    public static IQueryable<T> AutoSelect<T, TProject>(this IQueryable<T> q){ 
     // read TProject type in reflection 
     // create a projection as a IQueryable<T> 
    } 
} 

有什麼辦法嗎?我GOOGLE了它,但沒有找到任何資源。你能指導我嗎?

回答

1

是,有可能將實體框架實體自動投影到某些Dto。請參閱實現的一個在這裏https://gist.github.com/1367880

你可以使用它作爲:

context.Persons.Project().To<PersonNameModel>().ToList(); 

在DB查詢將產生只選擇需要的列(由PersonNameModel指定)的話。

如果您只想映射查詢結果(即檢索到的對象),那麼應該選擇EmitMapper或AutoMapper。

+0

偉大偉大。非常感謝 – 2012-08-29 17:37:40