How to tell entity framework code first to order the lazy loaded list - ef-code-first

Suppose I have the Following class
public class Account
{
public int AccountID {get; set;}
public string AccountName {get; set;}
public Account Parent { get; set; }
public virtual List<Account> Children { get; set; }
}
and I loaded list of accounts in a specific orderBy clause. my question is how can I tell entity framework code first to order the Children in a specific order when he lazy load that List?

Related

Entity Framework Core multiple table relationship

I am trying to create relationship where parent has many children and also includes the oldest child. How to correctly configure that relationship and how to insert the data into the tables?
public class Parent
{
public int Id { get; set; }
public int Name { get; set; }
public int ChildId { get; set; }
public virtual Child Child { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
public int Age { get; set; }
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
I would recommend against trying to store it as a separate property. Instead, calculate it from existing data with a get-only property something like:
public Child OldestChild => Childs.OrderByDescending(c => c.Age).FirstOrDefault();
If you are concerned about the cost of repeated access, you can look into wrapping the access logic using the Lazy<> class or some other caching methods. If you do, be aware that changes to the Childs collection would then not be reflected in the cached OldestChild result.
FOLLOW-UP: The above is still incomplete as it doesn't resolve cases of children of the same age - close birthdates, twins, adoptees, etc. That also raises the question: Why are are you modeling age (which changes over time vs Birthdate, which is fixed.

EF Code First access child of child to set ForeignKey

Below are the sample classes
public class Parent {
public int ParentId {get; set;}
public string UserName {get; set;}
public Child Child{get; set;}
}
public class Child {
public Child1[] ListChild1 {get; set;}
}
public class Child1 {
public int Child1Id {get; set;}
public int ParentId {get; set;}
public int Child1Name {get;set;}
}
Need to create the table using Entity Framework Code-First approach. ParentId is PK in Parent and FK in Child1. No need to create
table for Child class. Child1 table has Child1Id as PK and ParentId as FK. Need some help how to create this relationship in database
using fluent api.
Required Databse structure
Parent
ParentId (PK)
UserName
Child1
Child1Id (PK)
ParentId (FK)
ChildName
I have used something similar in the past :
public class Category
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public int? ParentID { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
}
This should work for an infinite parent, children relationship in the same table.

Tree structure with reference to root in Entity Framework

I'm trying to model a tree structure for orders in Entity Framework. Right now I've go the following:
public class ProjectModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CustomerId { get; set; }
public virtual List<ProjectNode> Nodes { get; set; }
}
public class ProjectNode
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Path { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual List<ProjectNode> Children { get; set; }
}
What I need to be able to do is get a reference to the root ProjectModel at any level of ProjectNode in order to authorize a given user actually having permission to view and change the project which contains the ProjectNode.
public class ProjectNode {
public int ProjectId { get; set; } //<-- this
...
public class ProjectModel {
[Key]
public int Id { get; set; } //<-- containing the value of this
}
My question is whether its possible to have a theoretical ProjectId property populated at every level of the tree structure, or if I need to set it manually.
I had something working that at first blush appeared to allow this functionality, but upon further investigation only populated the ProjectId for ProjectNodes contained in the ProjectModel's Nodes property.
It seems to me like it would be super inefficient to recurse backwards through the structure to get to the root.
Credit due to #TestWell for this answer -
Apparently, all I needed to do for EF to automatically populate the ProjectId property on the ProjectNode was to change the name of the Id property in ProjectModel to ProjectId.
Unfortunately, this doesn't appear to work if I add a CustomerId property to the ProjectNode that I would like automatically populated from the property of the same name on the node's root ProjectModel, which I realized is the more efficient solution to what I'm trying to do.

Effective approach to defining language-specific entities in EF code first

I am developing a multi-lingual ASP.NET web application that makes use of Entity Framework Code First for data persistance. For example I have defined an entity for my "Project" instance
public class Project
{
public Guid Id {get; set;}
public string Name {get; set;}
public string Descr {get; set;}
}
Now I want to add another language support, to allow admins to save different string data for different-language project description. Right now I have to just go ahead and add properties like
public string Name_Es {get; set;}
public string Descr_Es {get; set;}
and provide a specific logic to allow population of these language-specific fields.
Is there a more efficient way to allow saving of language-specific data via EF Code First?
Once we did a project project which has slimier acquirement. The Entities were like this,
public class Project
{
public Guid Id {get; set;}
public string Name {get; set;}
public string Descr {get; set;}
publis List<Translation> NameTranslations{get;set;}
}
public Translation
{
public int Id {get;set;}
public int LanguageId {get;set;}
public string Text{get;set;}
}
And on top of the EF layer we can use Automapper to map our domain object with a specific language to a DTO. So the Dto doesn't have all the language translations. We had a static variable that has the current language Id(Enum) and depend on that Automapper will select the correct translation from NameTranslations list.
public class ProjectDto
{
public Guid Id {get; set;}
public string Name {get; set;}
public string Descr {get; set;}
}
The advantage of this method than yours is we don't need to have columns for each and every language for each required columns. And if you want to add new language it's just adding new enum value and no changes for the domain objects.

Define association using database column and not entity type property

public class Order {
public int OrderID {get; set;}
public DateTime DateOrdered { get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderLine{
public int OrderLineID { get; set; }
public int OrderID {get; set; } // I want to remove this
public string ItemName { get; set;}
public Int Qty { get; set; }
}
How would I map these using the Fluent API? I am using these in a repository pattern where Order will be the root of the aggregate. As such I do not want OrderLine to have a reference to Order or have an OrderID. Since the OrderLine only makes any sense because its a child of Order.
Currently I am using this:
HasMany<OrderLine>(x => x.OrderLines).WithRequired().HasForeignKey(x => x.OrderID);
I am using an existing database structure here and ideally I would map this using the database column name. So somehow tell it to use tblOrderLine.colOrderId rather then OrderLine.OrderID.
You can use the Map() method to map your FK
HasMany<OrderLine>(x => x.OrderLines)
.WithRequired()
.Map(m => m.MapKey("colOrderId"));

Resources