Getting ObjectContext error even after calling ToList - entity-framework

When calling the method directly below I get a ObjectDisposedException when calling Mapper.Map with the retrieved list.
System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
public IEnumerable<Models.Provider> Get(string owner)
{
List<Data.Models.Provider> providers;
using (var db = new Data.ProviderDirectoryContext())
{
providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
}
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
I previously had the code like this (below), I wasn't getting an error, but the database was getting pounded when doing the mapping, and it was taking too long. I don't want to hit the database, when doing the mapping.
public IEnumerable<Models.Provider> Get(string owner)
{
using (var db = new Data.ProviderDirectoryContext())
{
var providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
}
How can I retrieve all the data before doing the mapping?
Here is the DbContext and the Data.Models.Provider for your reference.
public class ProviderDirectoryContext : DbContext
{
public DbSet<Owner> Owners { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<LocationAuditLog> LocationAuditLog { get; set; }
public DbSet<Office> Offices { get; set; }
public DbSet<OfficePhoneNumber> OfficePhoneNumbers { get; set; }
public DbSet<OfficeAuditLog> OfficeAuditLog { get; set; }
public DbSet<OfficeDay> OfficeDays { get; set; }
public DbSet<Provider> Providers { get; set; }
public DbSet<ProviderPhoneNumber> ProviderPhoneNumbers { get; set; }
public DbSet<ProviderAuditLog> ProviderAuditLog { get; set; }
public DbSet<ProviderType> ProviderTypes { get; set; }
public DbSet<ProviderSpecialty> ProviderSpecialties { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Provider>().HasRequired(cn => cn.Owner).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Office>().HasRequired(cn => cn.Owner).WithMany().WillCascadeOnDelete(false);
}
}
public class Provider
{
public int Id { get; set; }
public int OwnerId { get; set; }
public virtual Owner Owner { get; set; }
public int? ProviderTypeId { get; set; }
public virtual ProviderType ProviderType { get; set; }
public int? ProviderSpecialtyId { get; set; }
public virtual ProviderSpecialty ProviderSpecialty { get; set; }
[Required]
[StringLength(75)]
public string FirstName { get; set; }
[StringLength(75)]
public string MiddleName { get; set; }
[Required]
[StringLength(75)]
public string LastName { get; set; }
[StringLength(100)]
public string EmailAddress { get; set; }
public virtual ICollection<ProviderPhoneNumber> PhoneNumbers { get; set; }
public string Note { get; set; }
public DateTime? InactiveOn { get; set; }
public int OfficeId { get; set; }
public virtual Office Office { get; set; }
public virtual ICollection<ProviderAuditLog> AuditLog { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
[StringLength(75)]
public string CreatedBy { get; set; }
[Required]
public DateTime ModifiedOn { get; set; }
[Required]
[StringLength(75)]
public string ModifiedBy { get; set; }
}
Thanks for the help!

The problem is that the Models.Provider class contains other classes like Models.Office, and Models.PhoneNumbers that were not eagerly loaded by the query. In addition to that, the Models.Provider class needs to be flattened. The Mapper wants to recursively map everything, and it keeps going down to the next class. For example, Provider.Office.Location.Offices.
The solution is to flatten Models.Provider and add .Include() to the query so it eagerly loads the data required.
I'll clean this up a bit more, but this is currently working.
public IEnumerable<Models.Provider> Get(string owner)
{
List<Data.Models.Provider> providers;
using (var db = new Data.ProviderDirectoryContext())
{
providers = db.Providers
.Where(p => p.Owner.Name == owner)
.Include("ProviderType")
.Include("ProviderSpecialty")
.Include("Office")
.Include("PhoneNumbers")
.ToList();
}
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
public class Provider
{
public int Id { get; set; }
public int OwnerId { get; set; }
public int OfficeId { get; set; }
public string OfficeName { get; set; }
public int? ProviderTypeId { get; set; }
public string ProviderTypeName { get; set; }
public int? ProviderSpecialtyId { get; set; }
public string ProviderSpecialtyName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
public string Note { get; set; }
public DateTime? InactiveOn { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
}

I am not sure how much this will help with performance but declaring the variable you don't want to dispose outside the using statement should fix your dispose exception.
public IEnumerable<Models.Provider> Get(string owner)
{
IEnumerable<Models.Provider> dtoProviders;
using (var db = new Data.ProviderDirectoryContext())
{
List<Data.Models.Provider> providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
}
return dtoProviders;
}

Related

EFCore some Properties aren't populated

Im having the problem that some of my objects aren't populated fully and I can't understand why this happens I tested with the following code:
[HttpGet]
[Route("Artikel/Test")]
public async Task<IActionResult> Test()
{
return Json(await db.Artikel_Meldungen
.Include(m => m.Meldung).ThenInclude(a => a.ErsatzArtikel)
.Where(x=>x.Artikel_MeldungId==1726)
.ToListAsync());
}
[HttpGet]
[Route("Artikel/Meldung")]
public async Task<IActionResult> GetMeldungen()
{
return Json((await db.Artikel_Meldungen
.Include(m => m.Meldung).ThenInclude(a => a.ErsatzArtikel)
.ToListAsync())
.Where(x => x.Artikel_MeldungId == 1726));
}
with the following classes:
[Table("Meldung", Schema = "BDB")]
public class Meldung
{
[Key]
public int Meldung_Id { get; set; }
public string Erfasser { get; set; }
public Artikel ErsatzArtikel { get; set; }
[NotMapped]
public Artikel Parent { get; set; }
public long ErsatzArtNr { get; set; }
[Column(TypeName = "nvarchar(2)")]
public string ErsatzAusfKz { get; set; }
public virtual ICollection<Artikel_Meldung> Artikel_Meldungen { get; set; }
public string Kommentar { get; set; }
public DateTime StartZeitpunkt { get; set; }
public DateTime EndeZeitpunkt { get; set; }
}
[Table("Artikel_Meldung", Schema = "BDB")]
public class Artikel_Meldung
{
[Key]
public int Artikel_MeldungId { get; set; }
public int Meldung_Id { get; set; }
public Meldung Meldung { get; set; }
public Artikel Artikel { get; set; }
public long ArtNr { get; set; }
[Column(TypeName = "nvarchar(2)")]
public string Ausfkz { get; set; }
}
[Table("Artikeldaten_PRE", Schema = "BDB")]
public class Artikel
{
[Key]
public long ArtNr { get; set; }
[Column(TypeName = "nvarchar(2)")]
public string AusfKz { get; set; }
public virtual ICollection<Artikel_Meldung> Artikel_Meldungen { get; set; }
}
As for my understanding both should return the same result. But for some reason the "Artikel/Meldung" endpoint isn't populating the ErsatzArtikel object. Am I doing something wrong or is this a bug?
Regards Martin
Adding AsNoTracking() AsSplitQuery() fixed the issue

IAsyncEnumerable cannot be used for parameter of type IEnumerable

I have entities, service and view models. I use the service models in the services and in the service I map from entity to the service model and I return IQueryable<UserServiceModel> and I use the service in the controller but when I try to materialize the result and map it to the view model with Select it throw exception:
ArgumentException: Expression of type 'System.Collections.Generic.IAsyncEnumerable1[TestDriveServiceModel]' cannot be used for parameter of type 'System.Collections.Generic.IEnumerable1[TestDriveServiceModel]' of method 'System.Collections.Generic.List1[TestDriveServiceModel] ToList[TestDriveServiceModel](System.Collections.Generic.IEnumerable1[TestDriveServiceModel])'
Parameter name: arg0
// the service map from entities to service models and returns them
// userServiceModels is the result of the service
// Here the error is thrown
var viewModel = await userServiceModels.Select(usm => new UserViewModel()
{
TestDrivesCount = usm.TestDrives.Count()
}).ToListAsync();
public class UserServiceModel : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<TestDriveServiceModel> TestDrives { get; set; } = new List<TestDriveServiceModel>();
}
public class TestDriveServiceModel
{
public string Id { get; set; }
public string CarId { get; set; }
public CarServiceModel Car { get; set; }
public string UserId { get; set; }
public UserServiceModel User { get; set; }
public string StatusId { get; set; }
public StatusServiceModel Status { get; set; }
public DateTime ScheduleDate { get; set; }
public string Comment { get; set; }
}
public class User : IdentityUserEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<TestDriveEntity> TestDrives { get; set; } = new List<TestDriveEntity>();
}
public class TestDriveEntity
{
public string Id { get; set; }
[Required]
public string CarId { get; set; }
public BaseCarEntity Car { get; set; }
[Required]
public string UserId { get; set; }
public User UserEntity { get; set; }
[Required]
public string StatusId { get; set; }
public Status StatusEntity { get; set; }
[Required]
public DateTime ScheduleDate { get; set; }
public string Comment { get; set; }
}

Automapper maps source to destination but dest values are always null

I'm new to automapper and I'm having a problem with it. In this case the automapper is used to map models(EntityFramework generated) to my own viewmodels. This is what happens, the sourcemodel with it's values is mapped to a destinationmodel but the dest values are always null. What's going on with the values?
Now what did I do:
I referenced the automapper to my project and bootstrapped the mappings.
public static void RegisterAutoMapperMappings()
{
Mapper.Initialize(x =>
{
// Add the mappingprofiles you configured below
x.AddProfile(new RegistrationViewModelProfile());
});
}
public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
public class RegistrationViewModelProfile : Profile
{
protected override void Configure()
{
CreateMap<RegistrationViewModel, contact>().IgnoreAllUnmapped();
CreateMap<contact, RegistrationViewModel>().IgnoreAllUnmapped();
CreateMap<RegistrationViewModel, emailaddress>().IgnoreAllUnmapped();
CreateMap<emailaddress, RegistrationViewModel>().IgnoreAllUnmapped();
CreateMap<RegistrationViewModel, password>().IgnoreAllUnmapped();
CreateMap<password, RegistrationViewModel>().IgnoreAllUnmapped();
//Always check if mapping is valid
Mapper.AssertConfigurationIsValid();
}
}
My viewmodel:
public class RegistrationViewModel
{
public HttpPostedFileBase file { get; set; }
public String EmailAddress { get; set; }
public String Password { get; set; }
public string contact_givenname { get; set; }
public string contact_surname_prefix { get; set; }
public string contact_surname { get; set; }
public string contact_gender { get; set; }
public string contact_country { get; set; }
public string contact_residence { get; set; }
public Nullable<DateTime> contact_birth_date{ get; set; }
public DateTime create_date { get; set; }
public ICollection<int> Contact_roles { get; set; }
public string Emailaddress_verificationkey { get; set; }
}
My model:
public partial class contact
{
public contact()
{
this.contact_connection_rel = new HashSet<contact_connection_rel>();
this.contact_emailaddress_password_rel = new HashSet<contact_emailaddress_password_rel>();
this.contact_emailaddress_rel = new HashSet<contact_emailaddress_rel>();
this.contact_service_role_rel = new HashSet<contact_service_role_rel>();
this.given_answer = new HashSet<given_answer>();
this.given_answer1 = new HashSet<given_answer>();
}
public int contact_id { get; set; }
public string contact_initials { get; set; }
public string contact_givenname { get; set; }
public string contact_surname_prefix { get; set; }
public string contact_surname { get; set; }
public string contact_nickname { get; set; }
public string contact_gender { get; set; }
public Nullable<System.DateTime> contact_birth_date { get; set; }
public string contact_country { get; set; }
public string contact_residence { get; set; }
public string contact_ssn { get; set; }
public Nullable<System.DateTime> create_date { get; set; }
public Nullable<System.DateTime> modify_date { get; set; }
public Nullable<System.DateTime> delete_date { get; set; }
public virtual ICollection<contact_connection_rel> contact_connection_rel { get; set; }
public virtual ICollection<contact_emailaddress_password_rel> contact_emailaddress_password_rel { get; set; }
public virtual ICollection<contact_emailaddress_rel> contact_emailaddress_rel { get; set; }
public virtual ICollection<contact_service_role_rel> contact_service_role_rel { get; set; }
public virtual ICollection<given_answer> given_answer { get; set; }
public virtual ICollection<given_answer> given_answer1 { get; set; }
}
And to test the configuration the following lines are used. The vars contain the destination objects but are always null:
contact c = new contact();
contact testC = unitOfWork.ContactRepository.Find(82);
var x = Mapper.Map<contact, RegistrationViewModel>(testC);
var y = Mapper.Map(regModel, c, typeof(RegistrationViewModel), typeof(contact));
var b = Mapper.DynamicMap<RegistrationViewModel, contact>(regModel);
var z = Mapper.Map<RegistrationViewModel, contact>(regModel, c);
var w = Mapper.Map<RegistrationViewModel, contact>(regModel);
expression.ForAllMembers(opt => opt.Ignore());
You're telling AutoMapper to ignore all properties, so nothing gets mapped.
If you just want to ignore non-matching properties, see this answer for one way, otherwise you're going to have to explicitly map each property between the objects.

One to many relation with cascade giving error

I am learning EF Code First with migrations, I have 3 entities :
[User] 1--->* [Call] 1--->* [ETA]
Code :
User.cs
public class User
{
[Key]
public int Id { get; set; }
public Guid LongId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Call> Calls { get; set; } // many calls
public User()
{
LongId = Guid.NewGuid();
}
}
Call.cs
public class Call
{
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string BreakdownNo { get; private set; }
[Required,MaxLength(32)]
public string Customer { get; set; }
[Required,MaxLength(32)]
public string TrailerNo { get; set; }
[Required, MaxLength(32)]
public string DepotContact { get; set; }
[Required, MaxLength(48), RegularExpression(#"^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$")]
public string DepotEmail { get; set; }
[Required, MinLength(9), MaxLength(32)]
public string DepotPhone { get; set; }
[Required, MaxLength(32)]
public string DriverContact { get; set; }
[Required, MinLength(9), MaxLength(32), RegularExpression(#"^(7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$")]
public string DriverPhone { get; set; }
[Required, MaxLength(256)]
public string LocatedAtFreeText { get; set; }
[Required, MaxLength(8), RegularExpression(#"^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,1}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$")]
public string LocatedAtPostCode { get; set; }
[Required, MaxLength(16)]
public string StartupNo { get; set; }
[Required]
public bool IsLoaded { get; set; }
[Required, MaxLength(256)]
public string FaultDescription { get; set; }
[Required]
public DateTime StartTime { get; set; }
public DateTime? EndTime { get; set; }
public string Status { get; set; }
public virtual User Controller { get; set; } // 1 controller
public virtual ICollection<ETA> ETAs { get; set; } // many ETAs
public Call()
{
StartTime = DateTime.Now;
ETAs = new List<ETA> { new ETA() };
Status = "Logged";
}
}
ETA.c
public class ETA
{
[Key]
public int Id { get; set; }
[Required]
public TimeSpan Value { get; set; }
public int CallId { get; set; }
public ETA()
{
Value = TimeSpan.FromMinutes(90);
}
}
I would like it so when I delete the User it deletes all of the Calls for the User, which in turn deletes all of the ETAs for those Calls.
When I delete a User row from the Database (using database explorer) it gives me an error :
No rows were deleted.
A problem occurred attempting to delete row 201.
Error Source: .Net SqlClient Data Provider.
Error Message: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Calls_dbo.Users_Controller_Id". The conflict occurred in database "BreakdownDb", table "dbo.Calls", column 'Controller_Id'.
You can turn on the Cascade Delete option in Entity Framework, here you will find more info:
http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
The solution was to add OnModelCreating method to my DbContext class :
public class BreakdownDb : DbContext
{
public DbSet<Call> Calls { get; set; }
public DbSet<User> Users { get; set; }
public BreakdownDb(): base("name=DefaultConnection") {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Calls).WithRequired();
modelBuilder.Entity<Call>().HasMany(x => x.ETAs).WithRequired();
}
}

Entity Framework 4.3 CF many - to - many relationship saving object?

When creating many to many relationship using EF 4.3 code first approach, I cannot save data to connecting table, also cannot any examples on how to fill this table using saving object to Icollection... Here is my example:
MODELS
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
}
public class Project: DbContext
{
public DbSet<Hospital> Hospitals { get; set; }
public DbSet<Operator> Operators { get; set; }
}
CONTROLLER
public void AddOperater()
{
Hospital h = new Hospital();
h = db.Hospitals.Single(a=>a.Id ==1);
var o = new Operator();
o.FirstName = "John";
o.LastName = "Doe";
o.Dob = new DateTime(1988,2,12);
o.Email = "johndoe#gmail.com";
o.Hospitals.Add(h);
db.SaveChanges();
}
With this approach I keep getting error here: o.Hospitals.Add(h); even when my Hospital instance is filled with data. How exactly to save data to both tables, the dbo.Operators and dbo.OperatorHospital which is relationship table?
o.Hospitals.Add(h) will fail because the list is a null list. You cannot call Add() on a null list. Typically most people get around this by instantiating the list in the constructor of the entity... like so... the current line is blowing up due to a CSharp issue.
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
public Hospital()
{
Operators = new List<Operator>();
}
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
public Operator()
{
Hospitals = new List<Hospital>();
}
}