开发者

LINQ w/ Entity Framework -- filling objects

I'm not sure if this is possible with the Entity Framework but I'm duplicating too much code filling objects.

Currently my methods do something like:

return (from s in context.some_table
    join u in context.user_table on s.user_id equals u.id
    where s.id == someId
    select new MyObject()
    {
        TableColumn = s.some_column,
        User = new MyUser()
        {
            Username = u.username,
            Id = u.id,
        }
    }.FirstOrDefault();

I just typed that out as an example. I have a lot of queries where I include info about the user (more than just in that example). So in all of my queries I'm putting that same chunk of code in. If I have 100 methods with that chunk of code and I want to add another column t开发者_StackOverflow中文版hat's returned then I have to update 100 methods. Pain in the butt.

What I'd like to do is have the User object filled by a re-usable method. That way adding/removing columns returned only needs to be changed in one place. Like:

return (from s in context.some_table
    join u in context.user_table on s.user_id equals u.id
    where s.id = someId
    select new MyObject()
    {
        TableColumn = s.some_column,
        User = FillUser(u)
    }.FirstOrDefault();

FillUser would be the method. Of course this doesn't work with Entity Framework.

Is there anything I can do at all? I could of course return the whole user table but that's way more info than I need so it's a waste.

I'm using .NET 4.0 if that helps.


Entity framework is ORM tool so its main purpose is to define mapping from database to objects and load entities based on that mapping. Obviously if you need 100 times same user projection it is scenario for either mapped database view, custom defining query or custom query view. You are abusing projections instead of creating reusable mapping.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜