How to use Include method in LINQ To Entity when not sure that it has the specified navigation property? - entity-framework

I give you a CF example:
public class MyContext : DbContext
{
public DbSet<A> A { get; set; }
}
public class A
{
public int E { set; get; }
}
public class B : A
{
public int F { set; get; }
}
public class C : A
{
public int G { set; get; }
public virtual D D { set; get; }
}
public class D { }
and the query is like this:
using (var context = new MyContext())
{
var queryResult = context.A.Include("D").Select(a => a);
}
and it throws an exception with this message:
A specified Include path is not valid. The EntityType 'A' does not
declare a navigation property with the name 'D'.
How would you solve this with only one LINQ To Entity query?

Here is a work around
using (var context = new MyContext())
{
var typeA=typeOf(A);
var queryResult ;
if( typeA.GetProperty("D")!=null)
queryResult = context.A.Include("D").Select(a => a);
}

Related

How to declare a parent child relationship when both tables are TPH and the relationship is in the base classes?

My problem relates to sales orders and sales invoices but I find it easier to think of pets and their offspring... without creating a full pedigree model.
My DbContext
using System;
using DevExpress.ExpressApp.EFCore.Updating;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.ExpressApp.Design;
using DevExpress.ExpressApp.EFCore.DesignTime;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DevExpress.ExpressApp.DC;
using System.Collections.Generic;
namespace Pets.Module.BusinessObjects
{
[TypesInfoInitializer(typeof(PetsContextInitializer))]
public class PetsEFCoreDbContext : DbContext
{
public PetsEFCoreDbContext(DbContextOptions<PetsEFCoreDbContext> options) : base(options)
{
}
public DbSet<Cat> Cats { get; set; }
public DbSet<Dog> Dogs { get; set; }
public DbSet<Kitten> Kittens { get; set; }
public DbSet<Puppy> Puppys { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Pet>()
.HasDiscriminator(x=> x.IsCat)
.HasValue<Cat>(true)
.HasValue<Dog>(false);
modelBuilder.Entity<BabyPet>()
.HasDiscriminator(x => x.IsCat)
.HasValue<Kitten>(true)
.HasValue<Puppy>(false);
modelBuilder.Entity<Puppy>().HasOne(x => x.Parent).WithMany(x => x.Puppies);
modelBuilder.Entity<Kitten>().HasOne(x => x.Parent).WithMany(x => x.Kittens);
}
}
}
My classes
public abstract class Pet
{
[Key] public int Id { get; set; }
public string Name { get; set; }
public bool? IsCat { get; set; }
}
public abstract class BabyPet
{
[Key] public int Id { get; set; }
public int ParentPetId { get; set; }
[ForeignKey("ParentPetId")]
public virtual Pet Parent { get; set; }
public string Name { get; set; }
public bool? IsCat { get; set; }
}
public class Kitten : BabyPet
{
new public virtual Cat Parent { get; set; }
}
public class Dog : Pet
{
public Dog()
{
Puppies = new List<Puppy>();
}
[Aggregated]
public virtual List<Puppy> Puppies { get; set; }
}
public class Cat : Pet
{
public Cat()
{
Kittens = new List<Kitten>();
}
[Aggregated]
public virtual List<Kitten> Kittens { get; set; }
}
public class Puppy : BabyPet
{
new public virtual Dog Parent { get; set; }
}
Also there is
public class PetsContextInitializer : DbContextTypesInfoInitializerBase
{
protected override DbContext CreateDbContext()
{
var optionsBuilder = new DbContextOptionsBuilder<PetsEFCoreDbContext>()
.UseSqlServer(#";");
return new PetsEFCoreDbContext(optionsBuilder.Options);
}
}
However this creates the following structure in BabyPet
Where as I just want
[Update]
I was able to get the structure I want by specifying the foreignkey in OnModelCreating
modelBuilder.Entity<Puppy>().HasOne(x => x.Parent).WithMany(x => x.Puppies).HasForeignKey(x=>x.ParentPetId);
modelBuilder.Entity<Kitten>().HasOne(x => x.Parent).WithMany(x => x.Kittens).HasForeignKey(x => x.ParentPetId);
However when I try to add a Kitten to a cat via the XAF Winforms UI I get:
Unable to cast object of type 'SimplePets.Module.BusinessObjects.Kitten' to type 'SimplePets.Module.BusinessObjects.Puppy'.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.get_Item(IPropertyBase propertyBase)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.GetCurrentValue(IPropertyBase propertyBase)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, ICollection`1 propertiesToCheck, IPropertyBase property)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, IProperty property, ICollection`1 propertiesToCheck)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetPropertiesToCheck(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissionsForNonIntermediateObject(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissions(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckIsGrantedToSave(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetEntriesToSave(Boolean cascadeChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at DevExpress.ExpressApp.Win.SystemModule.WinModificationsController.Save(SimpleActionExecuteEventArgs args)
at DevExpress.ExpressApp.SystemModule.ModificationsController.saveAction_OnExecute(Object sender, SimpleActionExecuteEventArgs e)
at DevExpress.ExpressApp.Actions.SimpleAction.RaiseExecute(ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
I put my example on GitHub here
Docs link about relationships here and tph inheritance is here
I think I must have the data structures correct after my update to onModelCreating. That is :
modelBuilder.Entity<Puppy>().HasOne(x => x.Parent).WithMany(x => x.Puppies).HasForeignKey(x=>x.ParentPetId);
modelBuilder.Entity<Kitten>().HasOne(x => x.Parent).WithMany(x => x.Kittens).HasForeignKey(x => x.ParentPetId);
I was able to work around the Cast Object error by using DBContext instead of ObjectSpace
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using SimplePets.Module.BusinessObjects;
using System.Linq;
namespace SimplePets.Module.Win.Controllers
{
public class KittenViewController : ViewController
{
SimpleAction actionAddKittenEF;
SimpleAction actAddKittenXAF;
public KittenViewController() : base()
{
TargetObjectType = typeof(Kitten);
TargetViewNesting = Nesting.Nested;
actAddKittenXAF = new SimpleAction(this, "Add via OS", "View");
actAddKittenXAF.Execute += actAddKittenXAF_Execute;
actionAddKittenEF = new SimpleAction(this, "Add via Db", "View");
actionAddKittenEF.Execute += actionAddKittenEF_Execute;
}
private void actionAddKittenEF_Execute(object sender, SimpleActionExecuteEventArgs e)
{
var cat = View.ObjectSpace.GetObject(((NestedFrame)Frame).ViewItem.CurrentObject) as Cat;
var db = Helpers.MakeDb();
var kitten = new Kitten
{
Parent = db.Cats.FirstOrDefault(c => c.Id == cat.Id),
Name = $"baby {cat.Kittens.Count + 1} of {cat.Name}"
};
db.Kittens.Add(kitten);
db.SaveChanges();
View.ObjectSpace.Refresh();
}
//Errors
private void actAddKittenXAF_Execute(object sender, SimpleActionExecuteEventArgs e)
{
var cat = View.ObjectSpace.GetObject(((NestedFrame)Frame).ViewItem.CurrentObject) as Cat;
var os = View.ObjectSpace;
var kitten = os.CreateObject<Kitten>();
kitten.Parent = cat;
kitten.Name = $"baby {cat.Kittens.Count + 1} of {cat.Name}";
View.ObjectSpace.CommitChanges();
View.ObjectSpace.Refresh();
}
}
}

EF Core 6 Seeding Data Gives Foreign Key error Despite Having FK Value

So, I have struggled with this for a while now and can't figure out what I'm missing. I have a table that holds an entity called Skill and the DataModel looks like this:
public class SkillModel
{
public SkillModel()
{
}
public SkillModel(int skillId)
{
SkillId = skillId;
}
public int SkillId { get; set; } = 0;
public string Name { get; set; } = "";
public Guid DescriptionId { get; set; } = new();
public int SkillGroupId { get; set; } = 0;
public SkillGroupModel SkillGroup { get; set; } = new();
}
It references the SkillGroup which is it's own table and it looks like this:
public class SkillGroupModel
{
public SkillGroupModel()
{
}
public SkillGroupModel(int skillGroupId)
{
SkillGroupId = skillGroupId;
}
public int SkillGroupId { get; set; } = 0;
public string Name { get; set; } = "";
public Guid DescriptionId { get; set; } = new();
public List<SkillModel> Skills { get; set; } = new();
}
They each have their own configuration files and the look like this:
SkillModel
public class SkillConfiguration : IEntityTypeConfiguration<SkillModel>
{
public void Configure(EntityTypeBuilder<SkillModel> builder)
{
var dataSeeds = new DataSeeds();
builder.ToTable("Skills", "Skills");
builder.HasKey(k => k.SkillId);
builder.HasOne(s => s.SkillGroup)
.WithMany(s => s.Skills);
builder.HasData(dataSeeds.Skills);
}
}
SkillGroupModel
var dataSeeds = new DataSeeds();
builder.ToTable("SkillGroups", "Skills")
.HasKey(k => k.SkillGroupId);
builder.HasData(dataSeeds.SkillGroups);
Data seeds looks like this:
SkillGroupModel Seed
public List<SkillGroupModel> GetSkillGroups()
{
return new List<SkillGroupModel>()
{
new()
{
SkillGroupId = 1, Name = "Artisan", DescriptionId = SkillGroupDescriptions["Artisan"].Id
},
...
}
SkillModel Seeds
return new List<SkillModel>()
{
new()
{
SkillId = 1,
Name = "Aesthetics",
DescriptionId = SkillDescriptions["Aesthetics"].Id,
SkillGroupId = 1
},
...
}
So, I was obviously missing something. Ivan Stoev had a great point of not initializing my navigation properties like that, and that was a great help.
I went about it by not using my navigation properties and only setting the FK Properties. I think in the past I was trying to do both and that was causing issues that took me down this path. I'm not sure what I was doing wrong before but the way the documentation for seeding data on MSDN worked fine for me after going back and trying it again.

Map an Entity iEnumerator To Dto Enumerator

I am using CQRS. I select my Entities IEnumerator from database and i want to map this to my Dto class.
My Dto class:
public class XCollectionDto
{
public IEnumerable<XReadDto> Entries { get; init; } = Enumerable.Empty<XReadDto>();
}
My mapper class:
public class XReadMapper : IEntityToDtoMapper<X, XCollectionDto>
{
public XCollectionDto Map(IEnumerable <X> source, XCollectionDto target)
{
//todo
Here i want to map source to target Entries list
}
}
How can i do that, without a for loop? I am not using AutoMaper, the mapping is manual
I think you could accompish your purpose with C# reflection
I created the two class for test:
public class somemodel
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> Numlist { get; set; }
}
public class somemodelDTO
{
public int Id { get; set; }
public string SomeName { get; set; }
public List<int> Numlist { get; set; }
}
the method to bind properties of somemodelDTO which have the same name with properties of somemodel:
private static somemodelDTO GetMap<somemodel, somemodelDTO>(somemodel some)
{
somemodelDTO somemDTO = Activator.CreateInstance<somemodelDTO>();
var typesource = some.GetType();
var typedestination = typeof(somemodelDTO);
foreach(var sp in typesource.GetProperties())
{
foreach( var dp in typedestination.GetProperties())
{
if(sp.Name==dp.Name)
{
dp.SetValue(somemDTO, sp.GetValue(some, null), null);
}
}
}
return somemDTO;
}
The result:

Entity Framework Core 2.0: Error when enumerating over query with group

I have the following method which simply iterates over orders grouped by client ID.
static void LinqWithInto()
{
using (var db = new EFContext())
{
var orders = db.Orders.Include(o => o.Client);
orders.Load();
var query = from order in orders
group order by order.ClientId into g
select new { ClientId = g.Key, Count = g.Count(), Orders = g };
foreach (var group in query)
{
WriteLine($"Client Id: {group.ClientId}, Number of orders: {group.Count}");
foreach (var order in group.Orders)
WriteLine($"\tOrder Id: {order.OrderId}, Client Id: {order.Client.ClientId}, Client Name: " +
$"{order.Client.Name} Payment: {order.Payment}");
}
}
}
The query fetches orders with associated clients:
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public int ClientId { get; set; }
public double Payment { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
}
[Table("Client")]
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Order> Orders { get; set; }
}
The code works well in EF6, but in EF Core I get the following error (the variable query in foreach loop is highlighted):
System.ArgumentException: 'Expression of type 'System.Object' cannot be used for parameter of type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType' of method 'Void StartTracking(System.Object, Microsoft.EntityFrameworkCore.Metadata.IEntityType)''
I wonder what's wrong here?
This seems to be a bug in EF Core 2.0 which got addressed in this issue (Contains workaround):
https://github.com/aspnet/EntityFrameworkCore/issues/9551
You can get the testfeed 2.0.3 here (Contains fix):
https://github.com/aspnet/Announcements/issues/274
Here is a repro (which you should post over at GitHub), and a workaround. As Ivan said, that code doesn't make much sense, as the grouping query will still be sent to the database.
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
namespace efCoreTest
{
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public int ClientId { get; set; }
public double Payment { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
}
[Table("Client")]
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Order> Orders { get; set; } = new List<Order>();
}
class Db : DbContext
{
public DbSet<Client> Clients { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=efCoreTest;Integrated Security=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
class Program
{
static void Main(string[] args)
{
using (var db = new Db())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
for (int i = 0; i < 10; i++)
{
var client = new Client() { Address = "Address", Name = $"Client{i}" };
db.Clients.Add(client);
for (int j = 0; j < 5; j++)
{
var order = new Order() { Client = client, Payment = 20 };
db.Orders.Add(order);
}
}
db.SaveChanges();
}
using (var db = new Db())
{
//works
var orders = db.Orders.Include(o => o.Client).ToList() ;
//fails
//var orders = db.Orders.Include(o => o.Client);
// orders.Load();
var query = from order in orders
group order by order.ClientId into g
select new { ClientId = g.Key, Count = g.Count(), Orders = g };
foreach (var group in query)
{
Console.WriteLine($"Client Id: {group.ClientId}, Number of orders: {group.Count}");
foreach (var order in group.Orders)
Console.WriteLine($"\tOrder Id: {order.OrderId}, Client Id: {order.Client.ClientId}, Client Name: " +
$"{order.Client.Name} Payment: {order.Payment}");
}
Console.WriteLine("Complete");
Console.ReadKey();
}
}
}
}

TPC mappint generate the base class table

I want to achieve TPC mapping by code-first, and I have read this article:
Inheritance with EF Code First: Part 3 – Table per Concrete Type (TPC)
I've wrote the code as below.
namespace TPCTest
{
class Program
{
static void Main(string[] args)
{
using (TestContext context = new TestContext())
{
Manager m = new Manager();
m.AnnualSalary = 100000;
m.Name = "Allen";
m.Sex = true;
m.Id = 1;
Worker w = new Worker();
w.Id = 2;
w.Name = "John";
w.Sex = true;
w.MonthlyPay = 5000;
context.empSet.Add(m);
context.empSet.Add(w);
context.SaveChanges();
}
}
}
abstract class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public bool Sex { get; set; }
}
class Manager : Employee
{
public decimal AnnualSalary { get; set; }
public string Department { get; set; }
}
class Worker : Employee
{
public decimal MonthlyPay { get; set; }
}
class TestContext : DbContext
{
public DbSet<Employee> empSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Manager>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Manager");
});
modelBuilder.Entity<Worker>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Worker");
});
modelBuilder.Entity<Employee>().Property(e => e.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None);
}
}
}
But after running the code, I found the Employee table also exist in database, anyone can help?
Thanks in advance!
Use EF 5.0 or higher!
The issue seems to be fixed since that version. With EF 4.3.1 I could reproduce the behavior. So just update.