Best Way to convert one Edmx Entity to one Business entity - entity-framework

I am developing one application in which data is access from edmx entities and from that we have to fill each business entity after retriving data from edmx entity like:-
var tblproducts = tblproductsData
.Select(t => new tblProduct()
{
CategoryID = t.CategoryID,
Description = t.Description,
ID = t.ID,
Image = t.Image,
InsDt = t.InsDt,
Price = t.Price,
Quantity = t.Quantity,
Status = t.Status,
Title = t.Title,
tblCategory = new EFDbFirst.Models.tblCategory()
{
ID = t.tblCategory.ID,
status = t.tblStatus.StatusID,
Title_Category = t.tblCategory.Title_Category
},
tblStatu = new EFDbFirst.Models.tblStatu()
{
StatusDescription = t.tblStatus.StatusDescription
,
StatusID = t.tblStatus.StatusID
}
});
I am fadeup with this because everytime i have to convert one to another while getting data and setting data in db,
Is there any good way to create some common mehod which takes one anonymous type and converts it to another anonymous type.
Thanks in Advance

Your example isn't that clear.
First of all, EF doesn't work with anonymous types inside itself, it works with the EF types you have defined either using edmx file or code first. You can however create anonymous types yourself by defining an Select statement.
E.g:
var products = context.tblProductsData
.Select(r => new { Description = r.Description }); //new without typename is an
//anonymous object
The tblProduct, tblCategory and tblStatu objects, are they EF types? If so, you don't need to write a Select, EF will generate objects for you when you execute it.
E.g:
var products = context.tblProductsData.ToList();
This will automatically generate tblProduct objects for you. When you try to navigate to tblProduct.tblCategory or tblProduct.tblStatu, lazy loading will retrieve them for you. If you want to explicit load them during first query (eager-loading) use the Include function.
E.g:
var products = context.tblProductsData.Include(r => r.tblCategory)
.Include(r => r.tblStatu).ToList();
However if tblProducts, tblCategory and tblStatu is business objects and NOT EF types, there isn't any other way to do this, you have to explicit create them in a Select statement.

Related

Entity Framework select few fields from navigation property object

I have a simple query:
var car = CarRepository.GetById(1);
var engine = new EngineDto
{
Prop1 = car.Engine.Prop1,
Prop2 = car.Engine.Prop2,
Prop3 = car.Engine.Prop3,
Prop4 = car.Engine.Prop4
}
The issue is the Engine model has more then 50 columns and when I try to get value of Engine model property Entity Framework generate query
SELECT TOP(1) * FROM Engine WHERE ID = <id>
Is there any way to create query for getting only few fields?
Yes, there is a way: don't fetch the complete entity, but use Enumerable.Select to fetch only the data you plan to use.
For this your CarRepository would need a function that return IEnumerable<Car> (or similar IQueryable)
In two steps:
EngineDto engine = CarRepository.QueryCars() // function to fetch IEnumerable<Car>
.Where(car => car.Id == 1)
.Select(car => new EngineDto
{
Prop1 = car.Engine.Prop1,
Prop2 = car.Engine.Prop2,
Prop3 = car.Engine.Prop3,
Prop4 = car.Engine.Prop4,
})
.SingleOrDefault();
If the designer of the CarRepository didn't provide a function that would return a sequence of Cars, then obviously he thought that no one would ever want it. But I'm pretty sure the CarRepository has a function to "fetch all cars"
By the way, as transferring the data from the database to your local process is usually the slower part of your processing, it is always wise to transfer as little data as possible. Try to avoid transferring properties that you didn't plan to use.

How to Use Automapper on DTO Returned From EF?

I was told to use automapper in the code below. I cannot get clarification for reasons that are too lengthy to go into. What object am I supposed to be mapping to what object? I don't see a "source" object, since the source is the database...
Would really appreciate any help on how to do this with automapper. Note, the actual fields are irrelevant, I need help with the general concept. I do understand how mapping works when mapping from one object to another.
public IQueryable<Object> ReturnDetailedSummaries(long orgId)
{
var summaries = from s in db.ReportSummaries
where s.OrganizationId == orgId
select new SummaryViewModel
{
Id = s.Id,
Name = s.Name,
AuditLocationId = s.AuditLocationId,
AuditLocationName = s.Location.Name,
CreatedOn = s.CreatedOn,
CreatedById = s.CreatedById,
CreatedByName = s.User.Name,
OfficeId = s.OfficeId,
OfficeName = s.Office.Name,
OrganizationId = s.OrganizationId,
OrganizationName = s.Organization.Name,
IsCompleted = s.IsCompleted,
isHidden = s.isHidden,
numberOfItemsInAuditLocations = s.numberOfItemsInAuditLocations,
numberOfLocationsScanned = s.numberOfLocationsScanned,
numberOfItemsScanned = s.numberOfItemsScanned,
numberofDiscrepanciesFound = s.numberofDiscrepanciesFound
};
return summaries;
}
It is a handy and a timesaver, especially if you use a one to one naming between translations layers. Here is how I use it.
For single item
public Domain.Data.User GetUserByUserName(string userName)
{
Mapper.CreateMap<User, Domain.Data.User>();
return (
from s in _dataContext.Users
where s.UserName==userName
select Mapper.Map<User, Domain.Data.User>(s)
).SingleOrDefault();
}
Multiple Items
public List<Domain.Data.User> GetUsersByProvider(int providerID)
{
Mapper.CreateMap<User, Domain.Data.User>();
return (
from s in _dataContext.Users
where s.ProviderID== providerID
select Mapper.Map<User, Domain.Data.User>(s)
).ToList();
}
It looks like you already have a model? SummaryViewModel?
If this isn't the DTO, then presumably you want to do:
Mapper.CreateMap<SummaryViewModel, SummaryViewModelDto>();
SummaryViewModelDto summaryViewModelDto =
Mapper.Map<SummaryViewModel, SummaryViewModelDto>(summaryViewModel);
AutoMapper will copy fields from one object to another, to save you having to do it all manually.
See https://github.com/AutoMapper/AutoMapper/wiki/Getting-started
The source is your entity class ReportSummary, the target is SummaryViewModel:
Mapper.CreateMap<ReportSummary, SummaryViewModel>();
The best way to use AutoMapper in combination with an IQueryable data source is through the Project.To API:
var summaries = db.ReportSummaries.Where(s => s.OrganizationId == orgId)
.Project().To<SummaryViewModel>();
Project.To translates the properties in the target model straight to the selected columns in the generated SQL.
Mapper.Map, on the other hand, only works on in-memory collections, so you can only use it when you first fetch complete ReportSummary objects from the database. (In this case there may not be much of a difference, but in other cases it can be substantial).

Entity Framework AddObject not adding Object to EntitySet

I have the following piece of code
private void DoAddPropertyType()
{
var ctx = Globals.DbContext;
var propType = new PropertyType()
{
ID = Guid.NewGuid(),
Name = "NewType",
Description = "New Property Type",
ModifiedDate = DateTime.Now
};
ctx.AddToPropertyTypes(propType);
PropertyTypes.Add(propType);
}
Globals.DbContext provides a static reference to the objectcontext initiated on startup. For some reason the ctx.AddToPropertyTypes(propType); bit does not add the entity to the context. If I breakpoint after that line and browse the ctx.PropertyTypes entity set it is not there. Any ideas?
EDIT 1:
If I add a ctx.SaveChanges() after the ctx.AddToPropertyTypes(propType) and step the actual adding appears to happen only once SaveChanges execute. This however does not suit my requirements as I want to first validate objects prior to saving and wanted to iterate through the entities in the entity set. Does any one know of an alternative approach?
So that is the point of your issue. ctx.PropertyTypes is not a real collection - it is entrance to the database and your "browsing" actually executes query to the database where your new object was not yet stored. If you want to find a new object added to the context without saving it first you must search the object inside the ObjectStateManager:
var entity = ctx.ObjectStateManager
.GetObjectStateEntries(EntityState.Added)
.Where(e => !e.IsRelationship)
.Select(e => e.Entity)
.OfType<PropertyType>()
.SingleOrDefault(p => p.ID == ...);

In Entity Framework, take a newly created object and use it to update an existing record

Here's what I'd like to do:
var myCustomer = new Customer();
myCustomer.Name = "Bob";
myCustomer.HasAJob = true;
myCustomer.LikesPonies = false;
Then I'd like to pass it into an update method:
public UpdateCustomer(Customer cust)
{
using(var context = dbcontext())
{
var dbCust = context.Customers.FirstOrDefault(c => c.Name == cust.Name);
if(dbCust != null)
{
// Apply values from cust here so I don't have to do this:
dbCust.HasAJob = cust.HasAJob;
dbCust.LikesPonies = cust.LikesPonies
}
context.SaveChanges();
}
}
The reason for this is I'm working in multiple different parts of my application, and/or across DLLs. Is this possible?
EDIT: Found this question to be immensely useful:
Update Row if it Exists Else Insert Logic with Entity Framework
If you are sure that the entity is in the database and you have key you would just Attach the object you have to the context. Note that attached entities are by default in Unchanged state as the assumption is that all the values of properties are the same as in the database. If this is not the case (i.e. values are different) you need to change the state of the entity to modified. Take a look at this blog post: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx it describes several sceanrios including the one you are asking about.

Accessing foreign key value (int) in Entity Framework

I just spent the last 3-4 hours trying to retrieve a foreign key value using linq to entities and a stored procedure. Any advice is much appreciated.
public JsonResult GetEvents(double? start, double? end)
{
AnoEntities _dbAno = new AnoEntities();
var events = _dbAno.Events_GetByDateRange(fromDate, toDate);
var eventList = from e in events
select new
{
id = e.id,
title = e.title,
className = e.event_types.type.ToString()
};
return Json(eventList.ToArray());
}
type_id is the foreign key value that i'm trying to reach. I can't get it so appear in the entity data model and I can't seem to get to it. e.event_types and e.event_typesReference are both null so things like e.event_typesReference.EntityKey.EntityKeyValues.First().Value.ToString() aren't working.
Thanks!
I don't see any .Include methods or Load methods on even_types and I'm assuming your returning IEnumerable from your _dbAno.Events_GetByDateRange(fromDate, toDate). Like Craig pointed out in the comments if your return type of GetByDateRange is IQueryable you'd be projecting and EF should eager load for you.
Just a reminder that implicit lazy loading isn't supported out of the box in Entity Framework 1.0. You'll need to manually load the event_types with Load() or use the Include method on ObjectQuery.