Alternative to List.Include in EF - entity-framework

I am having circular reference due to the EF code below. I have a Parent table with 2 childs and their grandchildren respectively. Is there any alternative to using Include, as I read something about Navigation property and it includes the parents in each of the child, causing the serialization having circular reference problem.
Error Message:
A circular reference was detected while serializing an object of type 'Product'.
This part is only to get retrieval and I don't need the parent reference back to each of the child. I debug inside and saw that inside each of the child, it has the parent reference back.
var query = db.Products.Include(c => c.ProductTriggers.Select(b => b.ProductTriggerItems))
.Include(d => d.ProductsExtra.Select(e => e.ProductAllotments.Select(m => m.ProductAllotmentDetails))).AsNoTracking();
return query.ToList();
Product Class
public partial class Product
{
public Product()
{
this.ProductExtras = new HashSet<ProductExtra>();
this.ProductTriggers = new HashSet<ProductTrigger>();
}
public int ProductID { get; set; }
public string ProductCode { get; set; }
public string ProductName { get; set; }
public virtual ICollection<ProductProduct> ProductExtras { get; set; }
public virtual ICollection<ProductTrigger> ProductTriggers { get; set; }
}
ProductExtra Class
public partial class ProductExtra
{
public ProductExtra()
{
this.ProductAllotments = new HashSet<ProductAllotment>();
}
public int ProductExtraID { get; set; }
public int ProductID { get; set; }
public virtual Product Product { get; set; }
public virtual ICollection<ProductAllotment> ProductAllotments { get; set; }
}
ProductAllotment Class
public partial class ProductAllotment
{
public ProductAllotment()
{
this.ProductAllotmentDetails = new HashSet<ProductAllotmentDetail>();
}
public int ProductAllotmentID { get; set; }
public int ProductExtraID { get; set; }
public virtual ProductExtra ProductExtra { get; set; }
public virtual ICollection<ProductAllotmentDetail> ProductAllotmentDetails { get; set; }
}
ProductTrigger Class
public partial class ProductTrigger
{
public ProductTrigger()
{
this.AddOnTriggerItems = new HashSet<ProductTriggerItem>();
}
public int ProductTriggerID { get; set; }
public int ProductID { get; set; }
public virtual Product Product { get; set; }
public virtual ICollection<ProductTriggerItem> ProductTriggerItems { get; set; }
}
ProductTriggerItem Class
public partial class ProductTriggerItem
{
public int ProductTriggerItemID { get; set; }
public int ProductTriggerID { get; set; }
public virtual ProductTrigger ProductTrigger { get; set; }
}

Related

Entity Framework - 6, Parent Key propagation to grand child object

public class Submission
{
public Submission()
{
this.VisitOccurrences = new HashSet<VisitOccurrence>();
}
public int SubmissionKey { get; set; } //PK
public string Version { get; set; }
public string ClientName { get; set; }
public string UserName { get; set; }
public DateTime SubmissionStartDate { get; set; }
public virtual ICollection<VisitOccurrence> VisitOccurrences { get; set; }
}
public class VisitOccurrence
{
public VisitOccurrence()
{
this.Observations = new HashSet<VoObservation>();
}
public int VisitOccurrenceKey { get; set; } //PK
//public int SubmissionKey { get; set; } //FK from submission . This is commented as this value inserted by EF in table. Refer to configuration below.
public string VisitConcept { get; set; }
public DateTime? VisitStartDate { get; set; }
public TimeSpan? VisitStartTime { get; set; }
public DateTime? VisitEndDate { get; set; }
public TimeSpan? VisitEndTime { get; set; }
public virtual ICollection<Observation> Observations { get; set; }
}
public class Observation
{
public int ObservationKey { get; set; } //PK
//public int VisitOccurrenceKey { get; set; } //FK from VisitOccurrence. This is commented as this value inserted by EF in table. Refer to configuration below.
//public int SubmissionKey { get; set; } // ***there is no relation on this column but I need to propagate value from parent class Submission to this grand child column when inserted Submission. What is the best way to do it?***
public string Element { get; set; }
public string ObservationConcept { get; set; }
public DateTime? ObservationDate { get; set; }
public TimeSpan? ObservationTime { get; set; }
}
public class SubmissionConfiguration : EntityTypeConfiguration<Submission>
{
public SubmissionConfiguration()
{
ToTable("Submission");
HasKey(p => p.Id).Property(p => p.Id).HasColumnName("SubmissionKey");
HasMany(p => p.VisitOccurrences).WithOptional().Map(m => m.MapKey("SubmissionKey"));
}
}
public class VisitOccurrenceConfiguration : EntityTypeConfiguration<VisitOccurrence>
{
public VisitOccurrenceConfiguration()
{
ToTable("VisitOccurrence");
Property(p => p.Id).HasColumnName("VisitOccurrenceKey");
HasMany(p => p.Observations).WithOptional().Map(m => m.MapKey("VisitOccurrenceKey"));
}
}
public class ObservationConfiguration : EntityTypeConfiguration<Observation>
{
public VoObservationConfiguration()
{
ToTable("Observation");
}
}
//Repository Method to insert Submission
public virtual void AddOrUpdate(Submission model)
{
Context.Entry(model).State = EntityState.Added;
Context.SaveChanges();
}
I have a Parent entity Submission, a Child entity VisitOccurrence and Grand child entity Observation. My configurations works When I inserted a Submission with child and grand child entities in it. All key columns populated in related tables. However, The above code inserts Submission and the identity generated in SubmissionKey is inserted in VisitOccurence and thus the VisitOccurenceKey in Observation table. But I'm looking for Configuration that could propagate SubmissionKey from VisitOccurence to Observation though there is no relation constraint added in database. please help.

Returning Entity with its children

Hi I am trying to return all vehicles with their recorded mileage through an api using ASP.Net Core with the following code:
// GET: api/values
[HttpGet]
public IEnumerable<Vehicle> Get()
{
return _context.Vehicles.Include(m=>m.Mileages).ToList();
}
However this only returns the first vehicle with its mileages and not the others (there are five dummy vehicles in the db all with an initial mileage).
If I change the code to:
// GET: api/values
[HttpGet]
public IEnumerable<Vehicle> Get()
{
return _context.Vehicles.ToList();
}
it returns the full list of vehicles but no mileage.
My class files are:
public class Vehicle
{
public Vehicle()
{
Mileages = new List<Mileage>();
}
public int Id { get; set; }
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public ICollection<Mileage> Mileages { get; set; }
}
and
public class Mileage
{
public int Id { get; set; }
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
//Navigation Properties
public int VehicleId { get; set; }
public Vehicle Vehicle { get; set; }
}
thanks for looking!
Tuppers
you can have them auto-load (lazy loading) using proxies... but for that, your foreign entities and collections must be marked virtual in your POCOs:
public class Mileage
{
public int Id { get; set; }
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
//Navigation Properties
public int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
public class Vehicle
{
public Vehicle()
{
Mileages = new List<Mileage>();
}
public int Id { get; set; }
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public virtual ICollection<Mileage> Mileages { get; set; }
}
The proxy creation and lazy loading turned on, but that's the default in EF6.
https://msdn.microsoft.com/en-us/data/jj574232.aspx
Let me know if this works.
Well after a lot of searching I managed to find a solution. I used the following:
[HttpGet]
public IEnumerable<VehicleDto> Get()
{
var query = _context.Vehicles.Select(v => new VehicleDto
{
Registration = v.Registration,
Make = v.Make,
Model = v.Model,
Marked = v.Marked,
Mileages = v.Mileages.Select(m => new MileageDto
{
MileageDate = m.MileageDate,
RecordedMileage = m.RecordedMileage
})
.ToList(),
})
.ToList();
return (IEnumerable<VehicleDto>) query.AsEnumerable();
this doesn't seem to be the most elegant way of doing this, if anyone could offer any advice but it does return what is required.
The DTO's look like:
public class VehicleDto
{
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public ICollection<MileageDto> Mileages { get; set; }
}
and
public class MileageDto
{
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
}
Thanks for taking the time to look at this
Tuppers

Entity framework navigation property is null

I have two models using Entity Framework.
public class Player
{
public int PlayerId { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public string Plays { get; set; }
public string FavouriteSurface { get; set; }
}
public class SinglesMatch
{
public int SinglesMatchId { get; set; }
public int Player1Id { get; set; }
public int Player2Id { get; set; }
public int PlayerIdWinner { get; set; }
public DateTime Date { get; set; }
public string Venue { get; set; }
public string Score { get; set; }
public List<Player> Players { get; set; }
}
I am using the below code to attempt to display the Name of the player, based on the PlayerId in the SinglesMatch model matching the PlayerID from the Player model.
#foreach (var item in #Model)
{
<ul id="Players" class="bg-success"></ul>
<br/>
<h3>Date - #Html.DisplayFor(#modelItem => item.Date)</h3>
<li>Venue - #Html.DisplayFor(#modelItem => item.Venue)</li>
<li>Player 1 - #Html.DisplayFor(#modelItem => item.Players.First(p => p.PlayerId == item.Player1Id).Name)</li>
<li>Player 2 - #Html.DisplayFor(#modelItem => item.Players.First(p => p.PlayerId == item.Player2Id).Name)</li>
<li>Score- #Html.DisplayFor(#modelItem => item.Score)</li>
}
Upon debugging, the navigation property is always showing as null when the model is retrieved from my repository.
Am I using the navigation property in the correct fashion ? is there a problem with my query ?
Edit to include DbContext:
public TennisTrackerContext() : base("name=TennisTrackerContext")
{
}
public DbSet<Player> Players { get; set; }
public DbSet<PlayerRecord> PlayerRecords { get; set; }
public DbSet<SinglesMatch> SinglesMatches { get; set; }
public DbSet<DoublesMatch> DoublesMatches { get; set; }
public DbSet<Venue> Venues { get; set; }
}
}
You need to add a bridge table. Sql will create this automatically but you won't have access to the variables unless you create it in c#.
public class Player
{
public int PlayerId { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public string Plays { get; set; }
public string FavouriteSurface { get; set; }
List<PlayerInMatch> Matches { get; set; }
public Player()
{
Matches = new List<PlayerInMatch>();
}
}
public class PlayerInMatch
{
public int Id { get; set; }
public int PlayerId { get; set; }
[ForeignKey("PlayerId")]
public Player Player { get; set; }
public int SinglesMatchId { get; set; }
[ForeignKey("SinglesMatchId")]
public SinglesMatch SinglesMatch { get; set; }
}
public class SinglesMatch
{
public int SinglesMatchId { get; set; }
public int PlayerIdWinner { get; set; }
public DateTime Date { get; set; }
public string Venue { get; set; }
public string Score { get; set; }
public List<PlayerInMatch> Players { get; set; }
public SinglesMatch()
{
Players = new List<PlayerInMatch>();
}
}
static void Main(string[] args)
{
var match = new SinglesMatch();
match.Players.Select(c => c.Player.Name);
}
You need to make your navigation property virtual to enable lazy/eager loading:
public class SinglesMatch
{
public int SinglesMatchId { get; set; }
public int Player1Id { get; set; }
public int Player2Id { get; set; }
public int PlayerIdWinner { get; set; }
public DateTime Date { get; set; }
public string Venue { get; set; }
public string Score { get; set; }
public virtual List<Player> Players { get; set; }
}
Also, did you define the relationship between SinglesMatch and Singles in fluent api?
EDIT: I see you don't have any relations mapped through annotations or fluent api whatsoever, I suggest you take a look at this:
https://msdn.microsoft.com/en-us/data/jj591617.aspx

Code first fluent api - table relationship

I have following tables and need to set relationship between them.
Model classes for the tables are as given
public class UserAction
{
public int ActionID { get; set; }
public string ActionName { get; set; }
public virtual ICollection<RoleScreenActionPermission> RoleScreenActionPermissions { get; set; }
}
public class Screen
{
public int ScreenID { get; set; }
public string ScreenName { get; set; }
public virtual ICollection<RoleScreenActionPermission> RoleScreenActionPermissions { get; set; }
}
public class ScreenAction
{
public int ScreenActionID { get; set; }
public int ScreenID { get; set; }
public int ActionID { get; set; }
public virtual Screen Screen { get; set; }
public virtual UserAction UserAction { get; set; }
}
public class RoleScreenActionPermission
{
public int RoleScreenActionPermissionID { get; set; }
public int ScreenActionID { get; set; }
public int RoleID { get; set; }
public virtual ScreenAction ScreenAction { get; set; }
public virtual Role Role { get; set; }
}
The talbe structure created is as:
Please help with setting the relationship correctly.
Try to remove all your own foreign keys from your classes. EF must make it.
upd:
public class Screen
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Action
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ScreenAction
{
public int Id { get; set; }
public virtual Screen Screen { get; set; }
public virtual Action Action { get; set; }
}
public class RoleScreenActionPermission
{
public int Id { get; set; }
public virtual ScreenAction ScreenAction { get; set; }
public virtual Role Role { 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.