How can I order by many-to-many extra column in Entity Framework Core? - entity-framework

I am using Entity Framework Core 3. Member and Request entities are related many-to-many. But I have an extra column named Order. The member request order is saved in the MemberRequest table.
public class Member
{
public int MemberID { get; set; }
public string Name { get; set; }
public virtual ICollection<MemberRequest> MemberRequests { get; set; }
}
public class Request
{
public int RequestID { get; set; }
public string Message { get; set; }
public virtual ICollection<MemberRequest> MemberRequests { get; set; }
}
public class MemberRequest
{
[Key, Column(Order = 0)]
public int MemberID { get; set; }
[Key, Column(Order = 1)]
public int RequestID { get; set; }
public virtual Member Member { get; set; }
public virtual Request Request { get; set; }
public int Order { get; set; }
}
I want to get two select using Entity Framework Core:
public IEnumerable<Member> Get(int id)
{
var members = await _context.Request
.Include(e => e.MemberRequests)
.Where(e => e.MemberRequests.Any(m => m.RequestID == id))
.ToListAsync();
// How can I order by MemberRequest.Order ???
return member;
}
But I could not order result by MemberRequest.Order in MemberRequest entity. How can I do it?

Related

.NET Core: How to merge nested one-to-many relations in dto

How could merge nested child entity in parent?
I have these three entities:
public class Faculty
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Group> Groups { get; set; }
}
public class Group
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Expected results in ResultDto is:
public class ResultDto
{
public Guid FacultyId { get; set; }
public string FacultyName { get; set; }
public ICollection<User> Users { get; set; }
}
You're looking for SelectMany:
var results = context.Faculties.Select(f => new ResultDto
{
FacultyId = f.Id,
FacultyName = f.Name,
Users = f.Groups.SelectMany(g => g.Users).ToList()
}
This will run in EF-core versions like 5 and 6, also in 3, but slightly less efficiently.

EF Include and ThenInclude

I have a few models I am trying to bind with Include which is not returning back all expected related data. The full chain is:
User (one) > Role (one) > Permissions (Many) > Entity (One) > EntityArea (One)
These are my models: (CompanyBase is a base class with a companyId in it)
public class User : _CompanyBase
{
public int UserID { get; set; }
public string FullName { get; set; }
public int RoleID { get; set; }
public Role Role { get; set; }
}
public class Role : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleID { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
public ICollection<RolePermission> RolePermissions { get; set; }
public ICollection<User> Users { get; set; }
}
public class RolePermission : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RolePermissionID { get; set; }
public Guid Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string PermissionCode { get; set; }
public int RoleID { get; set; }
public Role Role { get; set; }
public int EntityID { get; set; }
public Entity Entity { get; set; }
}
public class Entity : _CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntityID { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string DisplayName { get; set; }
public int EntityAreaID { get; set; }
public EntityArea EntityArea { get; set; }
}
public class EntityArea :_CompanyBase
{
[Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntityAreaID { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
public ICollection<Entity> Entities { get; set; }
}
And I am trying to bind them with:
dbUser = db.Users
.AsNoTracking()
.Where(x => x.UserId == UserID)
.Include(m => m.Role)
.ThenInclude(m => m.RolePermissions)
.ThenInclude(m => m.Entity)
.ThenInclude(m => m.EntityArea)
.FirstOrDefault();
However, I do get the Role, I'm not getting anything further (Rolepermissions collection, Entity and Area). Is there something fundamentally I am doing wrong? This is a readonly query so hence notracking being used.
Thanks!
I don't think there is anything fundamentally wrong with your attempt. Have you checked if the specific user actually has any data in the connected tables?
Include() can sometimes generate a left join when you don't really need it, so I'd advise you to stay away from it when you can. I'd generally use a projection to specify the data I want to recieve. For your example this can be done with:
dbUser = db.Users
.AsNoTracking()
.Where(x => x.UserId == UserID)
.Select(x => new
{
Role = x.Role,
RolePermissions = x.RolePermissions,
Entity = x.Entity,
EntityArea = x.EntityArea
})
.FirstOrDefault();

EF Core could not be translated and will be evaluated locally

I have a query in EF Core 1.1.2 that is evaluated on client side and would like to know if there is a better way to translate it into sql?
The query:
from l in _ctx.Locations
join i in _ctx.Inventories on l.Id equals i.LocationId
join it in _ctx.Items on i.ItemId equals it.Id
where l.ProjectId == projectid
group i by new {l.Id, l.LHA} into il
select new InventoryLocations() {
Id= il.Key.Id,
LHA = il.Key.LHA,
FlaggedItems = il.Any(x=>x.Item != null && x.Item.Flagged)
}
If not, what other options do I have?
As I know there's still no way mapping views.
FromSQL() method can return types already known in the context only and I can not mark one model as [NotMapped] for example.
Moving back to ef6 is not an option because .net core is the target framework.
Models:
public class Location
{
public Guid Id { get; set; }
[ForeignKey("Project")]
public Guid ProjectId { get; set; }
public Project Project {get; set; }
public string Name { get; set; }
public string LHA { get; set; }
[ForeignKey("ScanUser")]
public Guid? ScanUserId { get; set; }
public User ScanUser { get; set; }
[ForeignKey("CheckUser")]
public Guid? CheckUserId { get; set; }
public User CheckUser { get; set; }
[ForeignKey("GroupLeader")]
public Guid? GroupLeaderId { get; set; }
public User GroupLeader { get; set; }
public int State { get; set; }
}
public class Inventory
{
public Guid Id { get; set; }
[ForeignKey("Project")]
public Guid ProjectId { get; set; }
public Project Project {get; set; }
public string EANCode { get; set; }
[ForeignKey("Location")]
public Guid LocationId { get; set; }
public Location Location { get; set; }
public Double ScanQty { get; set; }
[ForeignKey("ScanUser")]
public Guid? ScanUserId { get; set; }
public User ScanUser { get; set; }
public DateTime? ScanDate { get; set; }
[ForeignKey("Item")]
public Guid? ItemId { get; set; }
public Item Item { get; set; }
[ForeignKey("InventoryTask")]
public Guid? InventoryTaskId { get; set; }
public InventoryTask InventoryTask { get; set; }
[ForeignKey("CheckUser")]
public Guid? CheckUserId { get; set; }
public User CheckUser { get; set; }
public DateTime? CheckDate { get; set; }
public Double PrevQty { get; set; }
}
public class Item
{
public Guid Id { get; set; }
[ForeignKey("Project")]
public Guid ProjectId { get; set; }
public Project Project {get; set; }
public string ItemNo { get; set; }
public string EANCode { get; set; }
public string Name { get; set; }
public Double Price { get; set; }
public bool Deleted { get; set; }
public DateTime ChangeTime { get; set; }
public Double BaseQty { get; set; }
public bool Flagged { get; set; }
}
Currently (and looks like also in the incoming EF Core v.2.0) the GroupBy queries are processed locally, so the key is to avoid them where possible.
And your query seems to be eligible for that - there is no need to first multiply the data set with joins and then group it back.
I've noticed you use only reference navigation properties and FKs in your entities, basically like database table record and SQL. But EF allows you to define also a corresponding collection navigation properties which allow you to start queries from the logical root, thus eliminating the need of joins and group by.
If you define navigation property from Location to Inventory
public class Location
{
// ...
public ICollection<Inventory> Inventories { get; set; }
}
then the equivalent query could be simply:
from loc in _ctx.Locations
where loc.ProjectId == projectid
select new InventoryLocations()
{
Id = loc.Id,
LHA = loc.LHA,
FlaggedItems = loc.Inventories.Any(inv => inv.Item != null && inv.Item.Flagged)
}
which will be fully translated to SQL.
If for some reason you can't create the above collection navigation property, still you can start with locations and manually correlate them with inventories:
from loc in _ctx.Locations
where loc.ProjectId == projectid
select new InventoryLocations()
{
Id = loc.Id,
LHA = loc.LHA,
FlaggedItems = _ctx.Inventories.Any(inv => loc.Id == inv.LocationId && inv.Item != null && inv.Item.Flagged)
}
If you add the navigation property as Ivan correctly suggests:
public class Location
{
// ...
public ICollection<Inventory> Inventories { get; set; }
}
Then you can simply create a query like this:
var locations = _ctx.Locations
.Include(x => x.Inventories)
.ThenInclude(x => x.Item)
.Where(x => x.ProjectId == projectId)
.Select(loc => new InventoryLocations
{
Id = loc.Id,
LHA = loc.LHA,
FlaggedItems = loc.Inventories.Any(inv => inv.LocationId == loc.Id && inv.Item?.Flagged)
});

Using Automapper CreateMap to concatenate elements

I have the following EF classes:
public class Request
{
[Key]
public virtual int RequestID { get; set; }
...
public virtual List<RequestLinked> RequestLinkeds { get; set; }
}
public class RequestLinked
{
[Key, Column(Order = 0)]
[ForeignKey("Request")]
public int RequestID { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("RequestRelated")]
public int RequestRelatedID { get; set; }
public virtual Request Request { get; set; }
public virtual Request RequestRelated { get; set; }
}
I created a DTO like this:
[DataContract]
public class RequestDTO
{
[DataMember]
public int RequestID { get; set; }
...
[DataMember]
public string RequestRelatedIDs { get; set; }
}
Now I would like to use automapper fo fill my DTO object. I need to fill RequestRelatedIDs with all elements from RequestLinkeds.RequestRelatedID by concatenate all elements inside 1 string.
I tried this:
CreateMap<Request, RequestDTO>()
.ForMember(x => x.RequestRelatedIDs, o => o.MapFrom(src => string.Join(", ", src.RequestLinkeds.Select(x => x.RequestRelatedID));
But the Select method is red highlighted: System.Collections.Generic.List< PLATON.Domain.Models.RequestLinked >' does not contain a definition for 'Select'
Why is that not possible to perform a select? An alternative?
Thanks.

Entity Framework Code First Many to Many Setup For Existing Tables

I have the following tables Essence, EssenseSet, and Essense2EssenceSet
Essense2EssenceSet is the linking table that creates the M:M relationship.
I've been unable to get the M:M relationship working though in EF code first though.
Here's my code:
[Table("Essence", Schema = "Com")]
public class Essence
{
public int EssenceID { get; set; }
public string Name { get; set; }
public int EssenceTypeID { get; set; }
public string DescLong { get; set; }
public string DescShort { get; set; }
public virtual ICollection<EssenceSet> EssenceSets { get; set; }
public virtual EssenceType EssenceType { get; set; }
}
[Table("EssenceSet", Schema = "Com")]
public class EssenceSet
{
public int EssenceSetID { get; set; }
public int EssenceMakerID { get; set; }
public string Name { get; set; }
public string DescLong { get; set; }
public string DescShort { get; set; }
public virtual ICollection<Essence> Essences { get; set; }
}
[Table("Essence2EssenceSet", Schema = "Com")]
public class Essence2EssenceSet
{
//(PK / FK)
[Key] [Column(Order = 0)] [ForeignKey("Essence")] public int EssenceID { get; set; }
[Key] [Column(Order = 1)] [ForeignKey("EssenceSet")] public int EssenceSetID { get; set; }
//Navigation
public virtual Essence Essence { get; set; }
public virtual EssenceSet EssenceSet { get; set; }
}
public class EssenceContext : DbContext
{
public DbSet<Essence> Essences { get; set; }
public DbSet<EssenceSet> EssenceSets { get; set; }
public DbSet<Essence2EssenceSet> Essence2EssenceSets { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<Essence>()
.HasMany(e => e.EssenceSets)
.WithMany(set => set.Essences)
.Map(mc =>
{
mc.ToTable("Essence2EssenceSet");
mc.MapLeftKey("EssenceID");
mc.MapRightKey("EssenceSetID");
});
}
}
This is the code I'm trying to run:
Essence e = new Essence();
e.EssenceTypeID = (int)(double)dr[1];
e.Name = dr[2].ToString();
e.DescLong = dr[3].ToString();
//Get Essence Set
int setID = (int)(double)dr[0];
var set = ctx.EssenceSets.Find(setID);
e.EssenceSets = new HashSet<EssenceSet>();
e.EssenceSets.Add(set);
ctx.Essences.Add(e);
ctx.SaveChanges();
And here's the error:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception.
I'm not able to find the problem. I'd greatly appreciate help setting this up right.
Thanks!
Remove your Essence2EssenceSet model class. If junction table contains only keys of related entities participating in many-to-many relations it is not needed to map it as entity. Also make sure that your fluent mapping of many-to-many relations specifies schema for table:
mb.Entity<Essence>()
.HasMany(e => e.EssenceSets)
.WithMany(set => set.Essences)
.Map(mc =>
{
mc.ToTable("Essence2EssenceSet", "Com");
mc.MapLeftKey("EssenceID");
mc.MapRightKey("EssenceSetID");
});