开发者

How to cast an EF4.1 table class to a derived view class?

I have used Entity Framework and have generated edmx for my db. The generated template classes represent each table. I have a generated clas开发者_如何学Pythons 'Table' from which I have copied 4 out of it's 12 properties to a new interface 'ITableModel'.

var tables = (from t in db.Tables 
                        orderby t.DateReceived descending
                        select t).Take(100);

var list = tables.AsEnumerable().Cast<ITableModel>().ToList();

As you can proobably guess, the cast throws an invalidcast exception. The goal here is to prune out the info I need to pass to my views (MVC3) and create view classes that represent that information. From what I have gathered, this is the best practice, but I am against a wall with this casting. Any help would be appreciated!


If you don't need all data from Table then there is no need to transfer them from database. You can use:

public class MyProjection : ITableModel
{
     public int SomeField { get; set; }
     public string SomeField2 { get; set; }
}

And call your query as:

var list =  db.Tables 
              .OrderByDescending(t => t.DateReceived)
              .Take(100) 
              .Select(t => new MyProjection 
                   {
                       SomeField = t.SomeField,
                       SomeField2 = t.SomeField2
                   })
              .ToList();

Cast is possible only if you override operator for casting but it requires concrete type because operator must create instance of the target type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜