I have an auto generated class (Orders class) which references other objects. What i'm trying to accomplish is get
an order using the order id and the user related to that order.
However when loading the object it is taking 2 seconds to load it. I looked at the object and EF is populating the list
of all the dependent objects (Language, country, customer user).
How do i get only specific object like only the order properties and the user object ? I tried to accomplish that using
the below code but it is loading all the objects.
//Code for getting order id and user related to it
using (var _storeEntities = new StoreEntities())
{
var test = _storeEntities.Orders.Where(r => r.Id.ToString() == orderId).Include(x => x.User).ToList();
}
// Parent entity
public partial class StoreEntities: DbContext
{
public virtual DbSet<Orders> Orders { get; set; }
}
// Order object
public partial class Orders
{
public System.Guid Id { get; set; }
public bool IsActive { get; set; }
public System.DateTime OrderDate{ get; set; }
public Nullable<int> CustomerId { get; set; }
public string LanguageId { get; set; }
public Nullable<System.Guid> UserId { get; set; }
public string CountryId { get; set; }
public virtual Customer Customer{ get; set; }
public virtual User User{ get; set; }
public virtual Country Country { get; set; }
public virtual Language Language { get; set; }
}
You should disable Lazy loading in configuration
public class YourContext : DbContext
{
public YourContext ()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
Or only during your call
using (var _storeEntities = new StoreEntities())
{
_storeEntities .Configuration.LazyLoadingEnabled = false;
var test = _storeEntities.Orders.Where(r => r.Id.ToString() == orderId)
.Include(x => x.User).ToList();
}
Here is the MSDN article for every type of loading
https://msdn.microsoft.com/en-nz/data/jj574232.aspx
Disable lazy loading:
_storeEntities.Configuration.LazyLoadingEnabled = false;
In constructor or before the query you want to run.
Or just remove virtual keyword.
Also you can disable proxy creation which is used for lazy loading:
_storeEntities.Configuration.ProxyCreationEnabled = false;
Related
I have following RecipeModel, IngredientModel and RecipePartModel classes which represent the DTO classes for the frontend user:
public class RecipeModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public IEnumerable<RecipePartModel> RecipeParts { get; set; }
}
public class IngredientModel
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class RecipePartModel
{
public Guid Id { get; set; }
public IngredientModel Ingredient { get; set; }
public string Unit { get; set; }
public decimal Quantity { get; set; }
}
Here are my entity classes:
public class Recipe : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public virtual IEnumerable<RecipePart> RecipeParts { get; set; }
}
public class Ingredient : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
public virtual IEnumerable<RecipePart> RecipeParts { get; set; }
}
public class RecipePart : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public Ingredient Ingredient { get; set; }
public Recipe Recipe { get; set; }
public string Unit { get; set; }
public decimal Quantity { get; set; }
}
My question is - how can I map the Recipe to RecipeModel using AutoMapper? I tried something like this but I assume it is bad, because it just join all the RecipeParts for the whole database, am I correct?
public class DomainProfile : Profile
{
public DomainProfile()
{
CreateMap<Ingredient, IngredientModel>().ReverseMap();
CreateMap<Recipe, RecipeModel>()
.ForMember(x => x.RecipeParts, opt => opt.MapFrom(src => src.RecipeParts));
}
}
To answer your question about how to use AutoMapper to map a type to another type, there are many ways of doing this. Documentation is here: http://docs.automapper.org/en/stable/Getting-started.html.
I wrote a console app and got it working in the quickest way I know possible using your code. When I debug this, and check inside recipeModel, it references a list of RecipePartModels with a single RecipePartModel. Inside that RecipePartModel, it references an IngredientModel.
static void Main(string[] args)
{
var profile = new DomainProfile();
Mapper.Initialize(cfg => cfg.AddProfile(profile));
var recipe = new Recipe
{
RecipeParts = new List<RecipePart>
{
new RecipePart()
{
Ingredient = new Ingredient()
}
}
};
var recipeModel = Mapper.Map<Recipe, RecipeModel>(recipe);
Console.ReadKey();
}
To answer your concern about getting all recipes from the database, if you're using Entity Framework, it depends on if you have lazy loading turned on. Lazy loading ensures that, when you get a recipe from the database, the recipe parts will not be loaded. They will only be loaded when you access the recipe part directly later on in the program flow. Lazy loading is turned on by default so this is the default behaviour. If you turn it off, you've enabled eager loading which loads all recipe parts and in turn their ingredient.
This might help: http://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx.
There is nothing bad about this mapping. In fact you don't even need the ForMember call as this is the default convention. The mapping will simply convert each element in the entity child collection to a corresponding model object.
Of course, whether you load your entities in an efficient manner is another matter. If you load a large amount of Recipe entities, and lazy load the RecipeParts collections for each, you will have a major "SELECT N+1" problem. But this is not the fault of AutoMapper.
I am facing an issue with the Fluent API mapping in EF6. It is all set up, but for some reason, anytime I select an object, it is missing the child objects.
Lets start with the DbContext:
public partial class PMSContext : DbContext
{
public PMSContext() : base(nameOrConnectionString: "PmsDb")
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<Employee> employees { get; set; }
public DbSet<Project> projects { get; set; }
public DbSet<ProjectStep> projectSteps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Employee>().HasMany(e => e.Projects).WithMany(t => t.EmployeesWorkingOnProject).Map(m =>
{
m.MapLeftKey("EmployeeId");
m.MapRightKey("ProjectId");
m.ToTable("employee_project");
});
modelBuilder.Entity<ProjectStep>().HasRequired(p => p.Project).WithMany(s => s.ProjectSteps).Map(m => m.MapKey("Project")).WillCascadeOnDelete(true);
//modelBuilder.Entity<Project>().HasMany(p => p.ProjectSteps).WithRequired(ps => ps.Project).WillCascadeOnDelete(true);
modelBuilder.Entity<Employee>().HasOptional<Project>(e => e.LeaderOfProject).WithOptionalPrincipal(p => p.ProjectLeader).Map(m => m.MapKey("ProjectLeader"));
}
public Project FindProjectById(int id)
{
return this.projects.Find(id);
}
}
This is pretty much everything needed which plays into my issue.
I have set up a total of 3 model classes:
[DataContract(Namespace = "Shared")]
public class Employee
{
public Employee()
{
this.Projects = new List<Project>();
}
[DataMember]
public int ID { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public String JobDescription { get; set; }
[DataMember]
public String Department { get; set; }
[DataMember]
public String DirectDialing { get; set; }
[DataMember]
public bool Status { get; set; }
public virtual Project LeaderOfProject { get; set; }
[DataMember]
public virtual List<Project> Projects { get; set; }
}
[DataContract(Namespace = "Shared")]
public class Project
{
public Project()
{
this.EmployeesWorkingOnProject = new List<Employee>();
this.ProjectSteps = new List<ProjectStep>();
}
[DataMember]
public int ID { get; set; }
[DataMember]
public String Titel { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public DateTime EndDate { get; set; }
[DataMember]
public String Description { get; set; }
[DataMember]
public Employee ProjectLeader { get; set; }
[DataMember]
public bool Status { get; set; }
[DataMember]
public virtual List<Employee> EmployeesWorkingOnProject { get; set; }
[DataMember]
public virtual List<ProjectStep> ProjectSteps { get; set; }
}
[DataContract(Namespace = "Shared")]
[Table("project_step")]
public class ProjectStep
{
[DataMember]
public int ID { get; set; }
[DataMember]
public String Description { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public DateTime EndDate { get; set; }
[DataMember]
public Project Project { get; set; }
}
And the corresponding database setup:
Now to my problem. Whenever I execute the FindProjectById method it does return the proper object, but it is missing any reference to the childs. this means that
ProjectSteps
EmployeesWorkingOnProject
ProjectLeader
are not set. This also causes issues on my delete methods. I assume that this is an error in my OnModelCreating method, but I am not 100% sure.
Can anyone tell me what I am missing to fetch the child objects as well?
You have disabled lazy loading and proxies, but if you do not .Include() child entities then EF doesn't know to load them. To use .Include() you will need to use .SingleOrDefault() rather than Find. Otherwise you will need to go to the context to Load child collections/references.
Your FindProjectById() would look something like:
var project = this.Projects.Include(x=>x.ProjectLeader)
.Include(x=>x.EmployeesWorkingOnProject)
.Include(x=>x.ProjectSteps)
.SingleOrDefault(x=>x.ID == id);
return project;
A caveat around using SingleOrDefault vs. Find is that where Find will search local store then go to DB, Single/First/ etc. will go to DB. This means that a query is executed each time where Find may find an entity in the local memory store. if you're inserting records into the DB Context (and prior to save changes) searching for that entity will not return an entity that is in the local store, but hasn't been committed to the DB yet. (prior to SaveChanges())
Typically you do not want to return entities outside of the scope of the DbContext as lazy load proxies won't work so anything you don't pre-load will be #null. I generally rely on deferred execution, returning IQueryable then .Select() the various bits I care about into DTO/ViewModel POCO classes.
You can try change the lazy loading into true if you want to automatically load the child objects.
this.Configuration.LazyLoadingEnabled = true;
if the lazy loading is false, then you need to load the reference before accessing it.
im using entity framework code first. Here are my poco classes:
public class BusinessPartner
{
[Key]
public int BusinessPartnerID { get; set; }
[Required]
[StringLength(255)]
public string Title { get; set; }
[StringLength(255)]
public string Address { get; set; }
public virtual ICollection<BusinessPartnerLanguage> BusinessPartnerLanguage { get; set; }
}
public class Language
{
[Key]
public int LanguageID { get; set; }
[Required]
[StringLength(255)]
public string Title { get; set; }
[Required]
public bool Active { get; set; }
public virtual ICollection<BusinessPartnerLanguage> BusinessPartnerLanguage { get; set; }
}
public class BusinessPartnerLanguage
{
[Key, Column(Order = 0)]
public int BusinessPartnerID { get; set; }
[Key, Column(Order = 1)]
public int LanguageID { get; set; }
[Required]
public bool Default { get; set; }
public virtual BusinessPartner BusinessPartner { get; set; }
public virtual Language Language { get; set; }
}
when i create new entity in my controller like:
BusinessPartner bp = new BusinessPartner();
its navigation property - bp.BusinessPartnerLanguage is null,
so if i do something like :
bp.BusinessPartnerLanguage.Add(someEntity);
im getting null exception. I managed to work around this by changing virtual ICollection properties to :
private ICollection<BusinessPartnerLanguage> _BusinessPartnerLanguage;
public virtual ICollection<BusinessPartnerLanguage> BusinessPartnerLanguage
{
get { return this._BusinessPartnerLanguage ?? (this._BusinessPartnerLanguage = new HashSet<BusinessPartnerLanguage>()); }
set { _BusinessPartnerLanguage = value; }
}
But i wanna know why isnt this working in normal way as it should, and is there a better way to work around this problem. Thanks in advance.
It's because It is just a POCO entity, if the property never been set, it will be null.
When retrieving an object from db context, if you enable the proxy, EF will create a proxy entity. And if you mark the property as virtual, any access to the virtual property will load the relationship and initialize the collection (if it's null). And it's the same thing with eager loading.
But you can't load the relationship if the entity doesn't exist in the database (a new one), it has to be an existing entity.
If you have existing id, you can create the proxy programmatically and lazy loading will load the relationship and initialize the collection. But you have to use Create method instead of new operator.
A proxy instance will not be created if you create an instance of an
entity using the new operator. - MSDN
var context = ...
int existingBPID = ...
var bp = context.Set<BusinessPartner>().Create(); // BusinessPartnerLanguage = null
bp.BusinessPartnerID = existingBPID; // BusinessPartnerLanguage = null
context.Entry(bp).State = EntityState.Unchanged; // BusinessPartnerLanguage = null
var collection = bp.BusinessPartnerLanguage; // trigger lazy loading, BusinessPartnerLanguage != null
And you can also simplify the property as follow.
private readonly ICollection<BusinessPartnerLanguage> _BusinessPartnerLanguage
= new HashSet<BusinessPartnerLanguage>();
public virtual ICollection<BusinessPartnerLanguage> BusinessPartnerLanguage
{
get { return _BusinessPartnerLanguage; }
}
When I connect LINQPad to my custom assembly using POCO connection, I'm missing some of my entities. This is a project was handed off to me, so I'm not sure what exactly causes this.
This is what I see in LINQPad for my FooContext,
This is my project model,
This is a table that does not show up in LINQPad,
[Table("People")]
public class Person : DomainEntity
{
[Required, StringLength(50)]
public String GivenName { get; set; }
[Required, StringLength(50)]
public String Surname { get; set; }
public virtual ICollection<EmailAddress> EmailAddresses { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
public virtual ICollection<PhysicalAddress> PhysicalAddresses { get; set; }
public virtual ICollection<Login> Logins { get; set; }
public virtual ICollection<CompanyContact> CompanyContacts { get; set; }
}
Here's a table that does,
[Table("Tags")]
public class Tag
{
public int Id { get; set; }
public String Value { get; set; }
public virtual DomainEntity Entity { get; set; }
}
What determines what LINQPad shows for FooContext?
LINQPad uses the following logic to determine which entities to display in the Schema Explorer:
System.Data.Entity.Infrastructure.IObjectContextAdapter adapter = this;
var items = adapter.ObjectContext.MetadataWorkspace.GetItems (DataSpace.CSpace);
var container = (EntityContainer) items.First (i => i.BuiltInTypeKind == BuiltInTypeKind.EntityContainer);
var entities = container.BaseEntitySets.Where (b => b.BuiltInTypeKind == BuiltInTypeKind.EntitySet && b.ElementType != null && b.ElementType is EntityType);
entities.Dump(1);
Does your table show up when you run this code in LINQPad with your custom POCO data context selected?
I would like to get Exams and Test entities that have a UserTest entity with a UserId that is either equal to "0" or to a provided value. I had a number of suggestions but so far none have worked. One suggestion was to start by getting UserTest data and the other solution was to start by getting Exam data. Here's what I have when I used the UserTests as the source starting point.
I have the following LINQ:
var userTests = _uow.UserTests
.GetAll()
.Include(t => t.Test)
.Include(t => t.Test.Exam)
.Where(t => t.UserId == "0" || t.UserId == userId)
.ToList();
When I check _uow.UserTests with the debugger it's a repository and when I check the dbcontext's configuration.lazyloading then it is set to false.
Here's my classes:
public class Exam
{
public int ExamId { get; set; }
public int SubjectId { get; set; }
public string Name { get; set; }
public virtual ICollection<Test> Tests { get; set; }
}
public class Test
{
public int TestId { get; set; }
public int ExamId { get; set; }
public string Title { get; set; }
public virtual ICollection<UserTest> UserTests { get; set; }
}
public class UserTest
{
public int UserTestId { get; set; }
public string UserId { get; set; }
public int TestId { get; set; }
public int QuestionsCount { get; set; }
}
When I looked at the output I saw something like this:
[{"userTestId":2,
"userId":"0",
"testId":12,
"test":{
"testId":12,"examId":1,
"exam":{
"examId":1,"subjectId":1,
"tests":[
{"testId":13,"examId":1,"title":"Sample Test1",
"userTests":[
{"userTestId":3,
"userId":"0",
Note that it gets a UserTest object, then gets a test object and then an exam object. However the exam object contains a test collection and then it heads back down again and gets the different tests and the unit tests inside of those:
UserTest > Test > Exam > Test > UserTest ?
I have tried hard to ensure lazy loading is off and debug tell me it's set to false. I am using EF6 and WebAPI but not sure if that makes a difference as I am debugging at the C# level.
You can't avoid that the inverse navigation properties are populated by EF, no matter if you load related entities with eager or lazy loading. This relationship fixup (as already explained by #Colin) is a feature you can't turn off.
You could solve the problem by nullifying the unwished inverse navigation properties after the query is finished:
foreach (var userTest in userTests)
{
if (userTest.Test != null)
{
userTest.Test.UserTests = null;
if (userTest.Test.Exam != null)
{
userTest.Test.Exam.Tests = null;
}
}
}
However, in my opinion the flaw of your design is that you try to serialize entities instead of data transfer objects ("DTOs") that are specialized to the view where you want to send the data to. By using DTOs you can avoid the inverse navigation properties that you don't want altogether and maybe other entity properties that you don't need in your view. You would define three DTO classes, for example:
public class ExamDTO
{
public int ExamId { get; set; }
public int SubjectId { get; set; }
public string Name { get; set; }
// no Tests collection here
}
public class TestDTO
{
public int TestId { get; set; }
public string Title { get; set; }
// no UserTests collection here
public ExamDTO Exam { get; set; }
}
public class UserTestDTO
{
public int UserTestId { get; set; }
public string UserId { get; set; }
public int QuestionsCount { get; set; }
public TestDTO Test { get; set; }
}
And then use a projection to load the data:
var userTests = _uow.UserTests
.GetAll()
.Where(ut => ut.UserId == "0" || ut.UserId == userId)
.Select(ut => new UserTestDTO
{
UserTestId = ut.UserTestId,
UserId = ut.UserId,
QuestionsCount = ut.QuestionsCount,
Test = new TestDTO
{
TestId = ut.Test.TestId,
Title = ut.Test.Title,
Exam = new ExamDTO
{
ExamId = ut.Test.Exam.ExamId,
SubjectId = ut.Test.Exam.SubjectId,
Name = ut.Test.Exam.Name
}
}
})
.ToList();
You could also "flatten" the object graph by defining only a single DTO class that contains all the properties you need for the view:
public class UserTestDTO
{
public int UserTestId { get; set; }
public string UserId { get; set; }
public int QuestionsCount { get; set; }
public int TestId { get; set; }
public string TestTitle { get; set; }
public int ExamId { get; set; }
public int ExamSubjectId { get; set; }
public string ExamName { get; set; }
}
The projection would become simpler and look like this:
var userTests = _uow.UserTests
.GetAll()
.Where(ut => ut.UserId == "0" || ut.UserId == userId)
.Select(ut => new UserTestDTO
{
UserTestId = ut.UserTestId,
UserId = ut.UserId,
QuestionsCount = ut.QuestionsCount,
TestId = ut.Test.TestId,
TestTitle = ut.Test.Title,
ExamId = ut.Test.Exam.ExamId,
ExamSubjectId = ut.Test.Exam.SubjectId,
ExamName = ut.Test.Exam.Name
})
.ToList();
By using DTOs you do not only avoid the problems of inverse navigation properties but also follow good security practices to "white-list" the exposed property values from your database explicitly. Imagine you would add a test access Password property to the Test entity. With your code that serializes eagerly loaded full entities with all properties the password would get serialized as well and run over the wire. You don't have to change any code for this to happen and in the worst case you wouldn't be aware that you are exposing passwords in a HTTP request. On the other hand when you are defining DTOs a new entity property would only be serialized with your Json data if you add this property explicitly to the DTO class.
Your query will load all UserTests into the context where UserId == "0" || UserId == userId and you have eagerly loaded the related Test and its related Exams.
Now in the debugger you can see that the Exams are linked to some Tests in memory and are assuming that is because they have been lazy-loaded. Not true. They are in memory because you loaded all UserTests into the context where UserId == "0" || UserId == userId and you have eagerly loaded the related Test. And they are linked to the navigation property because EF performs a "fix-up" based on foreign keys.
The Exam.Tests navigation property will contain any entities loaded into the context with the correct foreign key, but will not necessarily contain all Tests linked to the Exam in the database unless you eagerly load it or turn on lazy loading
I believe that deferred execution causes nothing to happen unless something is actually read from userTests. Try to include var userTestsAsList = userTests.ToList() and check with the debugger if userTestsAsList contains the desired sequence.
As far as I can read your POCO-Relationships and your query, your Repo is returning what you asked for. But did you know you asked for this?
You are navigating from Grand-Child <UserTest> to Child <Test> to Parent <Exam>
Your Entity of <Exam> is being treated as a Grand-Child when it seems to be a Grand-Parent (in fact, a graph root) having children of <Test> who have children / grand-children of type <UserTest>.
As you are eager loading (and serializing?), of course your <Exam> should eager load its <Test> Collection, which should load their <UserTest> Collections.
By working your way down the graph, you are causing a full circle.
Did you mean to have the opposite relationships?
public class Exam
{
public int ExamId { get; set; }
public int TestId { get; set; }
public int SubjectId { get; set; }
public string Name { get; set; }
}
public class Test
{
public int TestId { get; set; }
public int ExamId { get; set; }
public string Title { get; set; }
public virtual ICollection<UserTest> UserTests { get; set; }
}
public class UserTest
{
public int UserTestId { get; set; }
public string UserId { get; set; }
public int TestId { get; set; }
public int QuestionsCount { get; set; }
public virtual ICollection<Exam> Exams { get; set; }
}
I'm making many assumptions about your data. This relationships simply makes more sense as real-world entities and by your usage. That Users have Tests and Exams rather than the reverse. If so, this relationship should work with your linq query.
If you try something like:
var userTest = _uow.UserTests
.GetAll()
.Where(t => t.UserId == "0" || t.UserId == userId)
.First();
var name = userTest.Test.Title;
Would your code throw an exception because the Test property hasn't been loaded? I suspect the problem is your repository is using LINQ to SQL and not LINQ to Entities. You can't turn off Lazy Loading with LINQ to SQL. You would have to show how your repository works to fix the problem in that case.
Is there any reson you are using "virtual" for your collections? If you're using "include", I would recommend getting rid of the "virtual"