Given the following POCO Code First Entities
public class Customer
{
public int CustomerId { get; set; }
public string CustomerTitle { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
...
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
Using linq you can get the Orders filled in by using the Include property as in
var cust = (from cust in context.Customer
where cust.CustomerId == 1
select cust)
.Include(ord => ord.Orders)
.FirstOrDefault();
I am trying to get the same result using paramaterised sql, using
Customer co = context.Customer.SqlQuery(
#"select [Customer].[CustomerId],
...
[Order].[OrderId] AS [OrderId],
...
from Customer join Order on Customer.CustomerId = Order.CustomerId where Customer.CustomerId = #custid", sqlParm)
.FirstOrDefault();
How do I get the Orders in co.Orders to be populated with the above command, it seems like I can't use the Include statement with SqlQuery. This is a very simplified example for illustrative purposes only, the actual queries will be more involved.
This is not possible at all. Direct SQL execution doesn't offer filling of navigation properties and you really can't use Include. You must execute two separate SQL queries to get Cutomer and her Orders.
I have used the following class structure as workaround:
public class Customer
{
public int CustomerId { get; set; }
}
public class Order
{
public Customer Customer { get; set; }
private int _customerId;
private int CustomerId { get { return _customerId; } set { Customer.CustomerId = _customerId = value; } }
public Order()
{
Customer = new Customer();
}
}
In this case you don't need to run the query twice, and the following query would give the order with customer:
db.Database.SqlQuery<Order>(
"select cu.CustomerId, ord.OrderId from Orders ord join Customer cu on cu.CustomerId=ord.CustomerId")
.ToList();
What worked for me was to access the related member before the using is closed.
public static Customer GetCustomer (int custid)
{
Customer co = null;
using (var context = new YourEntities())
{
// your code
co = context.Customer.SqlQuery(
#"select [Customer].[CustomerId],
...
[Order].[OrderId] AS [OrderId],
...
from Customer join Order on Customer.CustomerId = Order.CustomerId where Customer.CustomerId = #custid", sqlParm)
.FirstOrDefault();
// my addition
// cause lazy loading of Orders before closing the using
ICollection<Order> orders = co.Orders;
}
// can access co.Orders after return.
return (co);
}
Related
I am new to EF core. I have a Customer model with the usual properties (Name,Address,Email).
I need a property to calculate the current balance for the customer.
This will be quite an intensive computation (once many records are stored) so am I correct in thinking that it should be stored in a Method, rather than a calculated property?
I am assuming I need to add a method such as .GetCurrentBalance().
Where would I put this method?
Simplified code below:
My Customer Model
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public virtual IEnumerable<SalesInvoice> SalesInvoices{ get; set; }
}
My Sales Invoice Model
public class SalesInvoice
{
public int SalesInvoiceId { get; set; }
public int CustomerId { get; set; }
public virtual IEnumerable<SalesInvoiceDetail> SalesInvoiceDetails{ get; set; }
}
My Sales Invoice Detail Model
public class SalesInvoiceDetail
{
public int SalesInvoiceDetailId { get; set; }
public int Qty { get; set; }
public decimal UnitPrice { get; set; }
}
Create helper methods which returns desired results. Everything should play around IQueryable:
public class CustomerIdWithBalance
{
public int CustomerId { get; set; }
public decimal Balance { get; set; }
}
public class CustomerWithBalance
{
public Customer Customer { get; set; }
public decimal Balance { get; set; }
}
public static class BusinessLogicExtensions
{
public static IQueryable<CustomerIdWithBalance> GetCustomerIdAndBalance(this IQueryable<Customer> customers)
{
var grouped =
from c in customers
from si in c.SalesInvoices
from sid in si.SalesInvoiceDetails
group sid by new { c.CustomerId } into g
select new CustomerIdWithBalance
{
g.Key.CustomerId,
Balance = x.Sum(x => x.Qty * x.UnitPrice)
}
return grouped;
}
public static IQueryable<CustomerWithBalance> GetCustomerAndBalance(this IQueryable<CustomerIdWithBalance> customerBalances, IQueryable<Customer> customers)
{
var query =
from b in customerBalances
join c in customers on b.CustomerId equals c.CustomerId
select new CustomerWithBalance
{
Customer = c,
Balance = b.Balance
};
return query;
}
}
Later when you need to return that with API call (hypothetic samples)
var qustomerIdsWithHighBalance =
from c in ctx.Customers.GetCustomerIdAndBalance()
where c.Balance > 1000
select c.CustomerId;
var qustomersWithHighBalance =
ctx.Customers.GetCustomerIdAndBalance()
.Where(c => c.Balance > 1000)
.GetCustomerAndBalance(ctx.Customers);
var customersByMatchAndPagination = ctx.Customers
.Where(c => c.Name.StartsWith("John"))
.OrderBy(c => c.Name)
.Skip(100)
.Take(50)
.GetCustomerAndBalance(ctx.Customers);
You will get desired results without additional database roundtrips. With properties you may load too much data into the memory.
It is everything about using EF with its limitations. But world is not stopped because EF team is too busy to create performance effective things.
Let's install https://github.com/axelheer/nein-linq
And create extension methods around Customer
public static class CustomerExtensions
{
[InjectLambda]
public static TotalBalance(this Customer customer)
=> throw new NotImplmentedException();
static Expression<Func<Customer, decimal>> TotalBalance()
{
return customer =>
(from si in customer.SalesInvoices
from sid in si.SalesInvoiceDetails
select sid)
.Sum(x => x.Qty * x.UnitPrice));
}
}
And everything become handy:
var customersWithHighBalance =
from c in ctx.Customers.ToInjectable()
where c.TotalBalance() > 1000
select c;
var customersWithHighBalance =
from c in ctx.Customers.ToInjectable()
let balance = c.TotalBalance()
where balance = balance > 1000
select new CustomerWithBalance
{
Customer = c,
Balance = balance
};
var customersWithBalance =
from c in ctx.Customers.ToInjectable()
where c.Name.StartsWith("John")
select new CustomerWithBalance
{
Customer = c,
Balance = c.TotalBalance()
};
var paginated =
.OrderBy(c => c.Name)
.Skip(100)
.Take(50);
If you would prefer to calculate at property level. Add an InvoiceBal readonly field to the SalesInvoice model.
public class SalesInvoice
{
public double InvoiceBal => SalesInvoiceDetails.Sum(x => x.Qty * x.UnitPrice)
public virtual IEnumerable<SalesInvoiceDetail> SalesInvoiceDetails{ get; set; }
}
Add another TotalBalance readonly field to the Customer that sums the whole thing
public class Customer
{
public double TotalBal => SalesInvoices.Sum(x => x.InvoiceBal)
public virtual IEnumerable<SalesInvoice> SalesInvoices{ get; set; }
}
I have the following classes:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public List<Event> Events { get; set; }
}
public class Event
{
public int Id { get; set; }
public int UserId { get; set; }
public string EventText { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string Day { get; set; }
public string ColorIdentifier { get; set; }
public int Week { get; set; }
}
I'm trying to get all the users and their events with Dapper like this:
var sql = "SELECT u.Id, e.UserId, e.EventText FROM cpc.PLANNING_TOOL_USERS u LEFT JOIN cpc.PLANNING_TOOL_EVENTS e ON u.Id=e.UserId";
var result = SqlMapper.Query<User, Event, User>(connection, sql, (u, e) =>
{
if (u.Events == null)
u.Events = new List<Event>();
u.Events.Add(e);
return u;
}, splitOn: "Id, UserId");
The Id for the user is returned back, but the list of events is not populated. I have looked at many examples here on Stack Overflow regarding this, but I can't see what I'm doing wrong.
To omit the situation that SQL returns no data I have just mocked two user rows with SQL union.
User with Id=1 and one Event, and User with Id=2 and two Events.
SqlMapper.Query returns flat results that are best for 1 to 1 relation. You have one user to many events relation, so some helper storage needed to maintain that relation as a mapping thru the results. I have used .NET dictionary for that.
My code sample below:
// introducing temporary storage
var usersDictionary = new Dictionary<int, User>();
var sql = #"SELECT 1 Id, 1 UserId, 'EventText1' EventText
union SELECT 2 Id, 2 UserId, 'EventText2' EventText
union SELECT 2 Id, 2 UserId, 'Another EventText2' EventText";
var result = SqlMapper.Query<User, Event, User>(connection, sql, (u, e) =>
{
if (!usersDictionary.ContainsKey(u.Id))
usersDictionary.Add(u.Id, u);
var cachedUser = usersDictionary[u.Id];
if (cachedUser.Events == null)
cachedUser.Events = new List<Event>();
cachedUser.Events.Add(e);
return cachedUser;
}, splitOn: "UserId");
// we are not really interested in `result` here
// we are more interested in the `usersDictionary`
var users = usersDictionary.Values.AsList();
Assert.AreEqual(2, users.Count);
Assert.AreEqual(1, users[0].Id);
CollectionAssert.IsNotEmpty(users[0].Events);
Assert.AreEqual(1, users[0].Events.Count);
Assert.AreEqual("EventText1", users[0].Events[0].EventText);
Assert.AreEqual(2, users[1].Events.Count);
I hope that helped you solving your mapping issue and events being null.
I really love Dapper's simplicity and possibilities. I would like to use Dapper to solve common challenges I face on a day-to-day basis. These are described below.
Here is my simple model.
public class OrderItem {
public long Id { get; set; }
public Item Item { get; set; }
public Vendor Vendor { get; set; }
public Money PurchasePrice { get; set; }
public Money SellingPrice { get; set; }
}
public class Item
{
public long Id { get; set; }
public string Title { get; set; }
public Category Category { get; set; }
}
public class Category
{
public long Id { get; set; }
public string Title { get; set; }
public long? CategoryId { get; set; }
}
public class Vendor
{
public long Id { get; set; }
public string Title { get; set; }
public Money Balance { get; set; }
public string SyncValue { get; set; }
}
public struct Money
{
public string Currency { get; set; }
public double Amount { get; set; }
}
Two challenges have been stumping me.
Question 1:
Should I always create a DTO with mapping logic between DTO-Entity in cases when I have a single property difference or simple enum/struct mapping?
For example: There is my Vendor entity, that has Balance property as a struct (otherwise it could be Enum). I haven't found anything better than that solution:
public async Task<Vendor> Load(long id) {
const string query = #"
select * from [dbo].[Vendor] where [Id] = #id
";
var row = (await this._db.QueryAsync<LoadVendorRow>(query, new {id})).FirstOrDefault();
if (row == null) {
return null;
}
return row.Map();
}
In this method I have 2 overhead code:
1. I have to create LoadVendorRow as DTO object;
2. I have to write my own mapping between LoadVendorRow and Vendor:
public static class VendorMapper {
public static Vendor Map(this LoadVendorRow row) {
return new Vendor {
Id = row.Id,
Title = row.Title,
Balance = new Money() {Amount = row.Balance, Currency = "RUR"},
SyncValue = row.SyncValue
};
}
}
Perhaps you might suggest that I have to store amount & currency together and retrieve it like _db.QueryAsync<Vendor, Money, Vendor>(...)- Perhaps, you are right. In that case, what should I do if I need to store/retrive Enum (OrderStatus property)?
var order = new Order
{
Id = row.Id,
ExternalOrderId = row.ExternalOrderId,
CustomerFullName = row.CustomerFullName,
CustomerAddress = row.CustomerAddress,
CustomerPhone = row.CustomerPhone,
Note = row.Note,
CreatedAtUtc = row.CreatedAtUtc,
DeliveryPrice = row.DeliveryPrice.ToMoney(),
OrderStatus = EnumExtensions.ParseEnum<OrderStatus>(row.OrderStatus)
};
Could I make this work without my own implementations and save time?
Question 2:
What should I do if I'd like to restore data to entities which are slightly more complex than simple single level DTO? OrderItem is beautiful example. This is the technique I am using to retrieve it right now:
public async Task<IList<OrderItem>> Load(long orderId) {
const string query = #"
select [oi].*,
[i].*,
[v].*,
[c].*
from [dbo].[OrderItem] [oi]
join [dbo].[Item] [i]
on [oi].[ItemId] = [i].[Id]
join [dbo].[Category] [c]
on [i].[CategoryId] = [c].[Id]
join [dbo].[Vendor] [v]
on [oi].[VendorId] = [v].[Id]
where [oi].[OrderId] = #orderId
";
var rows = (await this._db.QueryAsync<LoadOrderItemRow, LoadItemRow, LoadVendorRow, LoadCategoryRow, OrderItem>(query, this.Map, new { orderId }));
return rows.ToList();
}
As you can see, my question 1 problem forces me write custom mappers and DTO for every entity in the hierarchy. That's my mapper:
private OrderItem Map(LoadOrderItemRow row, LoadItemRow item, LoadVendorRow vendor, LoadCategoryRow category) {
return new OrderItem {
Id = row.Id,
Item = item.Map(category),
Vendor = vendor.Map(),
PurchasePrice = row.PurchasePrice.ToMoney(),
SellingPrice = row.SellingPrice.ToMoney()
};
}
There are lots of mappers that I'd like to eliminate to prevent unnecessary work.
Is there a clean way to retrive & map Order
entity with relative properties like Vendor, Item, Category etc)
You are not showing your Order entity but I'll take your OrderItem as an example and show you that you don't need a mapping tool for the specific problem (as quoted). You can retrieve the OrderItems along with the Item and Vendor info of each by doing the following:
var sql = #"
select oi.*, i.*, v.*
from OrderItem
inner join Item i on i.Id = oi.ItemId
left join Vendor v on v.Id = oi.VendorId
left join Category c on c.Id = i.CategoryId";
var items = connection.Query<OrderItem, Item, Vendor, Category, OrderItem>(sql,
(oi,i,v,c)=>
{
oi.Item=i;oi.Item.Category=c;oi.Vendor=v;
oi.Vendor.Balance = new Money { Amount = v.Amount, Currency = v.Currency};
return oi;
});
NOTE: The use of left join and adjust it accordingly based on your table structure.
I'm not sure I understand your question a 100%. And the fact that no one has attempted to answer it yet, leads me to believe that I'm not alone when I say it might be a little confusing.
You mention that you love Dapper's functionality, but I don't see you using it in your examples. Is it that you want to develop an alternative to Dapper? Or that you don't know how to use Dapper in your code?
In any case, here's a link to Dapper's code base for your review:
https://github.com/StackExchange/dapper-dot-net
Hoping that you'd be able to clarify your questions, I'm looking forward to your reply.
In order to get practice with Entity Framework, I am creating a C# WinForms project, and I used the answer to the question in this link to join and display tables in a datagridview:
Two entities in one dataGridView
I have searched for a clean way to save (to the SQL Server database) the changes made in the datagridview. Is there a good, fast, short, clean way? I have seen some ugly attempts, and even if they work, I am turned off by their ugliness.
With one table only (no joins), calling .SaveChanges works fine.
Here is the class set up to hold the joined fields:
public class CustAndOrders
{
// Customer table
public Int64 Cust_Id { get; set; }
public string Cust_Name { get; set; }
public DateTime Cust_BDay { get; set; }
//Order table
public Int64 Order_Id { get; set; }
public decimal Order_Amt { get; set; }
public DateTime Order_Date { get; set; }
// OrderDetail table
public Int64 Item_Number { get; set; }
public decimal Item_Amt { get; set; }
}
Here is the code to display the joined info in a datagridview. Obviously, the SaveChanges call does not work...yet
AWModel.TestJLEntities dc;
private void button1_Click(object sender, EventArgs e)
{
dc = new AWModel.TestJLEntities();
var query = from c in dc.Customers
join o in dc.Orders on c.CustId equals o.CustId
join od in dc.OrderDetails on o.OrderId equals od.OrderId
orderby o.OrderDate ascending, c.CustId, o.OrderAmount
select new CustAndOrders
{
Cust_Id = c.CustId,
Cust_Name = c.CustName,
Cust_BDay = c.CustBday,
Order_Id = o.OrderId,
Order_Amt = o.OrderAmount,
Order_Date = o.OrderDate,
Item_Number = od.ItemNumber,
Item_Amt = od.ItemAmount
};
var users = query.ToList();
dataGridView1.DataSource = users;
}
private void button2_Click(object sender, EventArgs e)
{
try
{
dc.SaveChanges();
}
catch
{
MessageBox.Show("Error saving changes");
}
}
EF is not seeing your changes because your data grid view is not bound to the EF entities, but rather an object populated from it's entities:
select new CustAndOrders
{
Cust_Id = c.CustId,
Cust_Name = c.CustName,
Cust_BDay = c.CustBday,
Order_Id = o.OrderId,
Order_Amt = o.OrderAmount,
Order_Date = o.OrderDate,
Item_Number = od.ItemNumber,
Item_Amt = od.ItemAmount
};
One solution I can think of is to compose CustAndOrders of the entities themselves:
public class CustAndOrders
{
public Customer Customer { get; set; }
public Order Order { get; set; }
public OrderDetail OrderDetail { get; set; }
}
And then bind to those fields i.e.
{Binding Customer.CustId}
Or if you don't want to change your bindings then pass the EF entities into the CustAndOrders object and in your properties just get and set from the entities:
public class CustAndOrders
{
public Customer Customer { get; set; }
public Order Order { get; set; }
public OrderDetail OrderDetail { get; set; }
// Customer table
public Int64 Cust_Id
{
get
{ return Customer.CustId;}
set
{ Customer.CustId = value; }
}
... Do this for the rest of your properties
And then query looks like this:
var query = from c in dc.Customers
join o in dc.Orders on c.CustId equals o.CustId
join od in dc.OrderDetails on o.OrderId equals od.OrderId
orderby o.OrderDate ascending, c.CustId, o.OrderAmount
select new CustAndOrders { Customer = c, Order = o, OrderDetail = od };
Assuming I have Customer and Order objects, where one Customer can have many Orders (so the Order class has a CustomerId property), and I want to return a collection of all CustomerAndMostRecentOrder objects which are defined as follows:
public class CustomerAndMostRecentOrder
{
public Customer Customer { get; set; }
public Order MostRecentOrder { get; set; }
}
How would I write a Linq query which does this (I'm using Linq to SQL)?
You can use the following query:
from c in customers
select new CustomerAndMostRecentOrder
{
Customer = c,
MostRecentOrder = c.Orders.OrderByDescending(o => o.PurchaseDate).FirstOrDefault()
};
This will use a navigation property from customer to order. The MostRecentOrder is taken by ordering the Orders on some DateTime property and then loading the first one.
You will need to have an CreatedDate date in your Order table to get the most recent order. Then to get your CustomerAndMostRecentOrder object, do the following query:
from c in customers
join o in orders on c.ID equals o.CustomerID into co
select new CustomerAndMostRecentOrder
{
Customer = c,
MostRecentOrder = co.OrderByDescending(o => o.CreatedDate).FirstOrDefault()
}
public class CustomerAndMostRecentOrder
{
public CustomerAndMostRecentOrder(Customer customer, Order mostRecentOrder)
{
Customer = customer;
MostRecentOrder = mostRecentOrder;
}
public Customer Customer { get; set; }
public Order MostRecentOrder { get; set; }
}
public class Order
{
}
public class Customer
{
public IEnumerable<Order> GetOrders()
{
}
}
public static class UsageClass
{
public static void Sample(IEnumerable<Customer> allCustomers)
{
IEnumerable<CustomerAndMostRecentOrder> customerAndMostRecentOrders =
allCustomers.Select(customer => new CustomerAndMostRecentOrder(customer, customer.GetOrders().Last()));
}
}
As another alternative, you may want to take a look into the DataLoadOptions.AssociateWith discussed at http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.associatewith.aspx. Simply set your requirements on the context and you don't need to worry about filtering the children at the query level.