开发者

Entity Framework and POCO in repository pattern

开发者 https://www.devze.com 2023-02-03 13:16 出处:网络
I\'d like to get a IQueryable<User> being POCO. I have two functions in my repository which converts O/RM to POCO and vice versa. This works fine when saving or getting one user, but what about

I'd like to get a IQueryable<User> being POCO. I have two functions in my repository which converts O/RM to POCO and vice versa. This works fine when saving or getting one user, but what about getting an IQueryable of User?

public IQueryable<Domains.User> GetUsers()
{
    // This wont work because it can't convert to a store expression
    return context.JUsers.Select(u => ConvertUserORMToDomain(u));
}

Do I have to manually rewrite out my conversion on ea开发者_JS百科ch POCO domain in every IQueryable Method I have? I'd be better off without patterns if thats the case.

Converter: private Domains.User ConvertUserORMToDomain(ORM.JUser ormUser)


Well a couple of points.

Your using Entity Framework, so why do you need to project the ORM objects into DTO's? If your using pure POCO's, then you don't need any projection at all.

If you want to keep doing what your doing, you need an intermediary layer to mediate betwen your ORM objects and your POCO's.

For example, your repository:

public IQueryable<JUser> GetUsers() // Note how it returns JUser, not the POCO
{
   return context.JUsers;
}

then your service:

public Domains.User GetUserById(int userId)
{
   return repository
             .GetUsers() // IQueryable<JUser>
             .Where(x => x.UserId == userId) // filter based on business req
             .ToList() // materialize query on server
             .Select(u => ConvertUserOrmToDomain(u)); // project into POCO
}

In other words, you need a manager which knows how to materialize the queries based on the business requirement (in this case, getting a user on id), and how to translate the objects into your domain entities.

As i said though, this is a waste of time IMO - use POCO's to directly represent your domain models, then you don't need that conversion process.

0

精彩评论

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