Reputation: 43
I am beginner with EF and Linq, so I would like to know the difference and the advantages to use one or the other approach, for example I can see to get data between two tables that it is possible use something like that:
var usr = from cm in ctx.ConsumerName
join c in ctx.Consumer on cm.ConsumerId equals c.Id
where cm.ConsumerId == consumerId
select new { Nombre = cm.FirstName + cm.LastName, Email = c.Email };
likewise, something like that is possible:
var usr = ctx.ConsumerName.Include(x=>x.Consumer);
or something like that as well:
var consumer = ctx.Consumer.Find(id);
var vm = new ConsumerViewModel();
Mapper.CreateMap<Consumer, ConsumerViewModel>()
.ForMember(dest => dest.Consumer, opt => opt.MapFrom(src => src));
vm = Mapper.Map<Consumer, ConsumerViewModel>(consumer);
Can someone explain me which is the best approach to get data from my data base with MVC and EF??? Thanx
Upvotes: 0
Views: 4238
Reputation: 15188
There are a number of different ways to create and execute query with Entity Framework, such as LINQ, Entity SQL, etc. LINQ to Entities is mostly commonly used, I think it's a good way to get data from a database using EF. You can learn more bout LINQ here:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
From the code examples you provided, I think you're not very clear on what LINQ and Entity Framework is.
var usr = from cm in ctx.ConsumerName
join c in ctx.Consumer on cm.ConsumerId equals c.Id
where cm.ConsumerId == consumerId
select new { Nombre = cm.FirstName + cm.LastName, Email = c.Email };
Above is a LINQ query with join operator.
var usr = ctx.ConsumerName.Include(x=>x.Consumer);
Above is Eagerly Loading. Entity Framework supports three ways to load related data, eager loading, lazy loading and explicit loading.
var consumer = ctx.Consumer.Find(id);
var vm = new ConsumerViewModel();
Mapper.CreateMap<Consumer, ConsumerViewModel>().ForMember(dest => dest.Consumer, opt => opt.MapFrom(src => src));
vm = Mapper.Map<Consumer, ConsumerViewModel>(consumer);
Above is mapping collection of entities in EF with AutoMapper.
If you want to learn more about Entity Framework, take look at below link, there are many great articles written by experts.
http://msdn.microsoft.com/en-US/data/ee712907#ef6
Upvotes: 3