Filling child entity with Entity Framework SqlQuery - entity-framework-5

I have two entities in 1:n relationship: Category and Product.
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public virtual Product { get; set; }
}
public class context : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
Its possible to load products in every category by Eager loading.
context.Categories.Include(c=>c.Products).ToList()
How can I load products in every category in below query same as Eager loading?
var q = #"
SELECT Categories.*
JOIN Products
ON Category.CategoryId = Products.CategoryId";
var c = context.Categories.SqlQuery(q).ToList();
Its only a simple query. I need to use SqlQuery to execute some queries.

According to this explanation you can't:
the query should be written to ensure that it only returns entities that are really of the requested type
(my emphasis)
So it's only by lazy loading (if enabled) that you can load the Products of the categories after the SqlQuery has run, which will cause n+1 queries.

I don't think it is possible to materialize entities obtained from Sql query if the result contains multiple entity types.

Related

Conversion failed,when using AutoQuery in ServiceStack

I have the following AutoQuery function.
[Route("/cars/search")]
public class SearchCars : QueryDb<Car, CarDto>
{
public List<int> EquipmentIds { get; set; }
public List<int> ManufacturerIds { get; set; }
public List<int> ColourIds { get; set; }
}
The function works, when I do the following:
Cars/Search?ColourIds=1&format=json
Cars/Search?ManufacturerIds=1&format=json
but when I try to use
Cars/Search?EquipmentIds=1&format=json
I get "Conversion failed when converting the varchar value '[1]' to data type int.".
The difference between these fields is that Car object can have multiple EquipmentIds, but only one ColourId and ManufacturerId.
public class Car
{
[AutoIncrement]
public int Id { get; set; }
public Colour Colour { get; set; }
[Required]
public int ColourId { get; set; }
public Manufacturer Manufacturer { get; set; }
[Required]
public int ManufacturerId { get; set; }
[Required]
public List<Equipment> Equipment { get; set; }
[Required]
public List<int> EquipmentId { get; set; }
}
Do I have to define for which attribute the different parameters should be assigned too?
AutoQuery works by constructing an RDBMS query based on implicit conventions which is used to construct an SQL query that runs on the RDBMS.
Complex Types in OrmLite data models are blobbed by default which means they can't be queried in the RDBMS with SQL, so you wont be able to query it with AutoQuery.
You could create a hybrid Custom AutoQuery Implementation where you can apply any custom logic to filter the results of the AutoQuery results, something like...
public class MyQueryServices : Service
{
public IAutoQueryDb AutoQuery { get; set; }
//Override with custom implementation
public object Any(SearchCars query)
{
var equipmentIds = query.EquipmentIds;
query.EquipmentIds = null;
var q = AutoQuery.CreateQuery(query, base.Request);
var response = AutoQuery.Execute(query, q);
if (equipmentIds != null)
response.Results.RemoveAll(x => x.EquipmentId...);
return response.
}
}

Servicestack - possibility of mapping several POCO to one table

I'm looking for a way to map several POCO objects into single table in the ServiceStack.
Is it possible to do this in a clean way, without "hacking" table creation process?
As a general rule, In OrmLite: 1 Class = 1 Table.
But I'm not clear what you mean my "map several POCO objects into single table", it sounds like using Auto Mapping to populate a table with multiple POCO instances, e.g:
var row = db.SingleById<Table>(id);
row.PopulateWithNonDefaultValues(instance1);
row.PopulateWithNonDefaultValues(instance2);
db.Update(row);
If you need to maintain a single table and have other "sub" classes that maintain different table in the universal table you can use [Alias] so all Update/Select/Insert's reference the same table, e.g:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
[Alias(nameof(Poco))]
public class PocoName
{
public int Id { get; set; }
public string Name { get; set; }
}
[Alias(nameof(Poco))]
public class PocoAge
{
public int Id { get; set; }
public int Age { get; set; }
}
Although I don't really see the benefit over having a single table that you use AutoMapping to map your other classes to before using that in OrmLite.

ServiceStack - [Reference] or [Ignore]?

We have a DTO - Employee - with many (> 20) related DTOs and DTO collections. For "size of returned JSON" reasons, we have marked those relationships as [Ignore]. It is then up to the client to populate any related DTOs that they would like using other REST calls.
We have tried a couple of things to satisfy clients' desire to have some related Employee info but not all:
We created a new DTO - EmployeeLite - which has the most-requested fields defined with "RelatedTableNameRelatedFieldName" approach and used the QueryBase overload and that has worked well.
We've also tried adding a property to a request DTO - "References" - which is a comma-separated list of related DTOs that the client would like populated. We then iterate the response and populate each Employee with the related DTO or List. The concern there is performance when iterating a large List.
We're wondering if there a suggested approach to what we're trying to do?
Thanks for any suggestions you may have.
UPDATE:
Here is a portion of our request DTO:
[Route("/employees", "GET")]
public class FindEmployeesRequest : QueryDb<Employee> {
public int? ID { get; set; }
public int[] IDs { get; set; }
public string UserID { get; set; }
public string LastNameStartsWith { get; set; }
public DateTime[] DateOfBirthBetween { get; set; }
public DateTime[] HireDateBetween { get; set; }
public bool? IsActive { get; set; }
}
There is no code for the service (automagical with QueryDb), so I added some to try the "merge" approach:
public object Get(FindEmployeesRequest request) {
var query = AutoQuery.CreateQuery(request, Request.GetRequestParams());
QueryResponse<Employee> response = AutoQuery.Execute(request, query);
if (response.Total > 0) {
List<Clerkship> clerkships = Db.Select<Clerkship>();
response.Results.Merge(clerkships);
}
return response;
}
This fails with Could not find Child Reference for 'Clerkship' on Parent 'Employee'
because in Employee we have:
[Ignore]
public List<Clerkship> Clerkships { get; set; }
which we did because we don't want "Clerkships" with every request. If I change [Ignore] to [Reference] I don't need the code above in the service - the List comes automatically. So it seems that .Merge only works with [Reference] which we don't want to do.
I'm not sure how I would use the "Custom Load References" approach in an AutoQuery service. And, AFAIKT, the "Custom Fields" approach can't be use for related DTOs, only for fields in the base table.
UPDATE 2:
The LoadSelect with include[] is working well for us. We are now trying to cover the case where ?fields= is used in the query string but the client does not request the ID field of the related DTO:
public partial class Employee {
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
.
.
.
[References(typeof(Department))]
public int DepartmentID { get; set; }
.
.
.
public class Department {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
.
.
.
}
So, for the request
/employees?fields=id,departmentid
we will get the Department in the response. But for the request
/employees?fields=id
we won't get the Department in the response.
We're trying to "quietly fix" this for the requester by modifying the query.SelectExpression and adding , "Employee"."DepartmentID" to the SELECT before doing the Db.LoadSelect. Debugging shows that query.SelectExpression is being modified, but according to SQL Profiler, "Employee"."DepartmentID" is not being selected.
Is there something else we should be doing to get "Employee"."DepartmentID" added to the SELECT?
Thanks.
UPDATE 3:
The Employee table has three 1:1 relationships - EmployeeType, Department and Title:
public partial class Employee {
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
[References(typeof(EmployeeType))]
public int EmployeeTypeID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
[References(typeof(Title))]
public int TitleID { get; set; }
.
.
.
}
public class EmployeeType {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
}
public class Department {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
[Reference]
public List<Title> Titles { get; set; }
}
public class Title {
[PrimaryKey]
public int ID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
public string Name { get; set; }
}
The latest update to 4.0.55 allows this:
/employees?fields=employeetype,department,title
I get back all the Employee table fields plus the three related DTOs - with one strange thing - the Employee's ID field is populated with the Employee's TitleID values (I think we saw this before?).
This request fixes that anomaly:
/employees?fields=id,employeetypeid,employeetype,departmentid,department,titleid,title
but I lose all of the other Employee fields.
This sounds like a "have your cake and eat it too" request, but is there a way that I can get all of the Employee fields and selective related DTOs? Something like:
/employees?fields=*,employeetype,department,title
AutoQuery Customizable Fields
Not sure if this is Relevant but AutoQuery has built-in support for Customizing which fields to return with the ?fields=Field1,Field2 option.
Merge disconnected POCO Results
As you've not provided any source code it's not clear what you're trying to achieve or where the inefficiency with the existing solution lies, but you don't want to be doing any N+1 SELECT queries. If you are, have a look at how you can merge disconnected POCO results together which will let you merge results from separate queries based on the relationships defined using OrmLite references, e.g the example below uses 2 distinct queries to join Customers with their orders:
//Select Customers who've had orders with Quantities of 10 or more
List<Customer> customers = db.Select<Customer>(q =>
q.Join<Order>()
.Where<Order>(o => o.Qty >= 10)
.SelectDistinct());
//Select Orders with Quantities of 10 or more
List<Order> orders = db.Select<Order>(o => o.Qty >= 10);
customers.Merge(orders); // Merge disconnected Orders with their related Customers
Custom Load References
You can selectively control which references OrmLite should load by specifying them when you call OrmLite's Load* API's, e.g:
var customerWithAddress = db.LoadSingleById<Customer>(customer.Id,
include: new[] { "PrimaryAddress" });
Using Custom Load References in AutoQuery
You can customize an AutoQuery Request to not return any references by using Db.Select instead of Db.LoadSelect in your custom AutoQuery implementation, e.g:
public object Get(FindEmployeesRequest request)
{
var q = AutoQuery.CreateQuery(request, Request);
var response = new QueryResponse<Employee>
{
Offset = q.Offset.GetValueOrDefault(0),
Results = Db.Select(q),
Total = (int)Db.Count(q),
};
return response;
}
Likewise if you only want to selectively load 1 or more references you can change LoadSelect to pass in an include: array with only the reference fields you want included, e.g:
public object Get(FindEmployeesRequest request)
{
var q = AutoQuery.CreateQuery(request, Request);
var response = new QueryResponse<Employee>
{
Offset = q.Offset.GetValueOrDefault(0),
Results = Db.LoadSelect(q, include:new []{ "Clerkships" }),
Total = (int)Db.Count(q),
};
return response;
}

How to design DTO classes for nested domain objects?

I am new to using DTOs.
I have two domain classes:
Category
Product
as follows
public class Category
{
// Properties
public int Id { get; set; }
public string Name { get; set; }
// Navigation properties
public virtual Category ParentCategory { get; set; }
// Foreign key
public int? ParentCategoryId { get; set; }
// Collections
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Category> Subcategories { get; set; }
}
public class Product
{
// Properties
public int Id { get; set; }
public string Name { get; set; }
// Navigation property
public virtual Category Category { get; set; }
// Foreign key
public int CategoryId { get; set; }
}
I want to use Automapper.
I am not sure how to design DTOs for the above aggregate (graph).
Should CategoryDTO have a collection of type ProductDTO or a collection of type Product?
Should ProductDTO have a CategoryDTO as navigation property or a Category or just an Id to the Category?
Can anyone suggest the code for DTOs?
How should this structure be flattened (if it should) and mapped to domain classes?
Many thanks in advance.
I design my DTOs to be only the data used for a specific controller action for MVC. Typically this means if I have a CategoryController, then I have a CategoryIndexModel, CategoryDetailsModel, CategoryEditModel etc etc. Only include the information you want on that screen. I flatten as much as I can, I don't create child DTOs unless I have a Partial or collection.

Fetching results from more than one IRepository

I have a list of Users and Orders.
public class UserRecord
{
public virtual int UserId { get; set; }
public virtual string Name { get; set; }
}
public class OrderRecord
{
public virtual int UserId { get; set; }
public virtual int OrderId { get; set; }
}
I have two repositories - IRepository and IRepository. How can I join the two and fetch the result, like this?
SELECT UserRecord.UserId, Name, OrderId
FROM UserRecord, OrderRecord
WHERE UserRecord.UserId = OrderRecord.UserId
Thanks.
Use the HQL API that is on ContentManager instead. Repository is for simple CRUD operations on a single table.

Resources