LINQ to Entities – Query Types
I have been doing a lot of work in MVC lately. Specifically, working with a WCF backend service which serves up data for the MVC UI layer. The layers are quite structured but the base layer of the entire application is the Data Project
. This project is a series of repository classes and related interface classes. All other projects reference the data project and this means that the Data project is the only layer that can access the database. All other layers call the interface methods of the Data project.
Here is an example of a repository which uses LINQ to Entities to call data from the database via Entity Framework.
EntityRepository.cs:
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using Entity = MyProject.Domain.DataPocos.Entity;
namespace MyProject.Data.Repository
{
public class EntityRepository<CONTEXT> : RepositoryBase<CONTEXT, Entity>, IEntityRepository<CONTEXT> where CONTEXT : dbEntities
{
IDatabaseFactory<CONTEXT> databaseFactory = null;
public EntityRepository(IDatabaseFactory<CONTEXT> databaseFactory) : base(databaseFactory)
{
this.databaseFactory = databaseFactory;
}
public IEnumerable<Entity> GetLeftJoinEntities()
{
var db = this.DataContext;
var entity = db.Entity;
return (from e in entity
from j in m.JoinedEntity.DefaultIfEmpty()
select new
{
Id = e.Id,
Name = e.Name,
IsVisible = e.IsVisible,
IsSelected = j != null ? true : false,
JoinedEntityId = j != null ? j.Id : 0
}).ToList()
.Select(x => new Entity
{
Id = x.Id,
Name = x.Name,
IsVisible = x.IsVisible,
IsSelected = x.IsSelected,
JoinedEntityId = x.JonedEntityId
}
).Where(x => x.IsVisible == true);
}
public IEnumerable<Entity> GetAllEntities()
{
var db = this.DataContext;
var entity = db.Entity;
return (from e in entity
select e);
}
}
}
Here is the interface that exposes the repository to the rest of the solution.
IEntityRepository.cs:
using System.Collections.Generic;
using System.Linq;
using MyProject.Domain.DataPocos;
namespace MyProject.Data.Repository
{
public interface IEntityRepository<dbEntities>
{
IEnumerable<Entity> GetAllEntities();
IEnumerable<Entity> GetLeftJoinEntities();
}
}
I hope this helps some of you with abstraction and separation of concerns. I will continue to share code samples whenever I get chance so feel free to comment and ask questions or make suggestions.
Til next time ...