Inserting item into DataGrid - c#

I have the following tables:
I'm using Entity Framework Database First, therefore the following entity class is generated:
public partial class Sal1 {
public string SaleID { get; set; }
public string ItemID { get; set; }
public int Quantity { get; set; }
public decimal Total { get; set; }
public virtual Item Item { get; set; }
public virtual Sale Sale { get; set; }
}
Then put the Sal1 rows into a datagrid like this:
private List<Sal1> saleItems = new List<Sal1>();
...
var query = from sa in db.Sal1
where sa.SaleID.Equals(tempSale)
select sa;
foreach(Sal1 si in query) {
saleItems.Add(si);
}
...
dgDetails.ItemsSource = saleItems;
But it turns out like this:
My question is, how should I tweak the query above so that I get the equivalent of the following SQL:
select T0.SaleID, T0.ItemID, T1.Name, T0.Quantity, T0.Total
from Sal1 T0 inner join Item T1 on T0.ItemID = T1.ItemID;
Thanks in advance.
EDIT: I seem to have found a solution, but I had to do this:
var query = from sa in db.Sal1
where sa.SaleID.Equals(tempSale)
select new { sa.SaleID, sa.ItemID, sa.Item.Name,
sa.Item.Manufacturer, sa.Quantity, sa.Total };
And I had to change the type of saleItems to object.
private List<object> saleItems = new List<object>();
Is this the best way to do it?

Just like SQL, LINQ also supports JOINs. You can read more about their syntax here. You should change your query accordingly to get your results. Instead of spoonfeeding the exact answer, I'm guiding you to a more detailed explanation, as it contains valuable information that will help you in the future too.

Related

Simple Linq query that joins two tables and returns a collection

I have two tables LookUpCodes and LookUpValues they are defined as below:
public partial class LookUpCodes
{
public int Id { get; set; }
public int? CodeId { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
public partial class LookUpValues
{
public int Id { get; set; }
public int CodeId { get; set; }
public string CodeValue { get; set; }
public bool? IsActive { get; set; }
}
Each LookUpCode can have multiple Values associated with it. I want to pass in a code and get associated list of values back.
This is probably a common question as I have seen this everywhere, I am not looking for an answer per se, if someone can just explain how to build the proper query I would be obliged.
Here is what I have done so far:
public IEnumerable<LookUpValues> GetValuesByCode(string cd)
{
var query = from code in _context.LookUpCodes
join values in _context.LookUpValues on code.CodeId equals values.CodeId
where code.Code == cd
select new { LookUpValues = values };
return (IEnumerable<LookUpValues>) query.ToList();
}
You are very close to that you are looking for:
public IEnumerable<LookUpValues> GetValuesByCode(string cd)
{
var query = from code in _context.LookUpCodes
join values in _context.LookUpValues
on code.CodeId equals values.CodeId
where code.Code == cd
select values;
return query;
}
Since you have written the join, I assume that you have understood how it works. However let's revisit it:
from a in listA
join b in listB
on a.commonId equals b.commonId
In the above snippet we join the contents of listA with the contents of listB and we base their join on a commonId property existing in items of both lists. Apparently the pair of a and b that fulfill the join criterion it would form one of the possible many results.
Then the where clause is applied on the results of the join. The joined items that pass thewherefilter is the new result. Even at this point the results is still pairs ofaandb`.
Last you project, using the select keyword each pair of the results to a new object. In your case, for each pair of code and values that passed also the where filter, you return only the values.

LINQ: Populating a LIST<> via multiple navigations

Ok, I'll try and make this make sense.
In a model, Lead, among other properties, we have these:
public class Lead
{
....
public int LeadID {get; set; }
public virtual ICollection<QuoteRevision> QuoteRevisions { get; set; }
....
}
And QuoteRevision...
public class QuoteRevision
{
....
[ForeignKey(nameof(LeadID))]
public virtual Lead Lead { get; set; }
public virtual ICollection<QuoteRevisionProduct> QuoteRevisionProduct{ get; set; }
....
}
And the model for QuoteRevisionProduct:
public class QuoteRevisionProduct
{
....
[ForeignKey(nameof(QuoteRevisionID))]
public virtual QuoteRevision QuoteRevision { get; set; }
[ForeignKey("ProductID")]
public virtual Product Product { get; set; }
....
}
And last of all...
public class Product
{
....
public string Code { get; set; }
....
}
Ok. So these are the models I need to query to build an object called QuoteSearchItem that has multiple properties. Here's two of them:
public class QuoteSearchItem
{
....
public LeadID {get; set; }
public List<string> Codes { get; set; }
....
}
I'm starting with this IQueryable of all rows in Lead:
leads = IQueryable<Lead>
And then doing this:
var results = from l in leads
from qr in l.QuoteRevisions
from rp in qr.RevisionProducts
select new QuoteSearchItem
{
....
LeadID = l.LeadID,
AdditionalProducts = ???
....
};
I'm not sure how to get that list of Codes. I can do this:
Code = rp.Product.Code,
And that will get me a single code, the first in the list. But how do I get ALL that match?
I know this was a lot to follow. I hope it makes sense. Thank you!
EDIT:
This is (almost) the SQL that I'm looking for:
SELECT
l.ID,
p.Code
FROM
dbo.Leads AS l
JOIN QuoteRevisions qr ON qr.LeadID = l.ID
JOIN QuoteRevisionProducts qrp on qrp.QuoteRevisionID = qr.QuoteRevisionID
JOIN Products p on p.ProductID = qrp.ProductID
Except that this will just return multiple rows per product. But, at least it gives an idea.
EDIT 2:
Code = l.QuoteRevisions.SelectMany(qr => qr.RevisionProducts).Select(p => p.Product.Code).ToList()
This doesn't throw an error, but it's returning a row of data for each code, which isn't what I need.
You can use SelectMany to flatten the models and get all the codes, something like this:
var results = from l in leads
select new QuoteSearchItem
{
....
LeadID = l.LeadID,
Codes = l.QuoteRevisions.SelectMany(qr => qr.QuoteRevisionProduct)
.Select(p => p.Product.Code)
....
};
not sure how your DB looks, but you can probably use Distinct as well to eliminate duplicate Codes

Dapper: mapping hierarchy and single different property

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.

Can any one help in casting below linq query?

Here is my linq to sql query which is working fine but when i cast and return the data I get casting error.
var productImages = from prod in context.seller_productinventory.AsEnumerable()
join prodImage in context.seller_productimages on prod.prdid equals prodImage.prdid
join category in context.mstr_scategory on prod.mcid equals category.CategoryID
join subcategory in context.mstr_scategory on prod.scid equals subcategory.CategoryID
select new
{
ProductId = prod.prdid,
Category = category.CategoryName,
Subcategory = subcategory.CategoryName,
Image1 = prodImage.image1Path,
Image2 = prodImage.image2Path,
Image3 = prodImage.image3Path,
Image4 = prodImage.image4Path,
ProductStatusCd = (Convert.ToInt32(prod.isAdminApproved) != 1) ? "Pending Approval" : "Approved"
};
I get error in below code.
return (IEnumerable<ProductImageModel>) productImages.ToList();
My Model Class:
public class ProductImageModel
{
public int ProductId { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public string Image1 { get; set; }
public string Image2 { get; set; }
public string Image3 { get; set; }
public string Image4 { get; set; }
public string ProductStatusCd { get; set; }
}
You are selecting an anonymous object using select new and later you are trying to cast a collection of anonymous objects to IEnumerable<ProductImageModel>, that will fail.
You have two options to fix that.
If your class ProductImageModel is not generated through entity framework then you can use that in your select statement like:
select new ProductImageModel
{
//.... fields
}
Or the other option is to create a temporary template class, and project your fields to that class object.
Remember, If ProductImageModel is framework generated then you can't use that in column projection using select.
From your code, it seems that your class ProductImageModel is actually representing a table from database. You will be needing another class (DTO) with fields specified in select clause.
public class ProductImageModelDTO
{
//your fields
}
and then in your LINQ query:
select new ProductImageModelDTO
{
ProductId = prod.prdid,
//rest of the fields.
Your method return type in that case should be:
IEnumerable<ProductImageModelDTO>
When you do select new { ... }, you're creating anonymous objects. Essentially, you end up with IQueryable<object> and that is contravariant with IEnumerable<ProductImageModel> (i.e., the compiler cannot cast from one to the other). The easiest solution is to select actual ProductImageModels if that's what you're going to use:
select new ProductImageModel
{
...
}
Then, no casting is necessary.

LINQ to SQL Group by C# problem

I recently started to use LINQ to SQL and i have a minor complex query i need help with.
I've got a table in my database called MovieComment, with the following columns:
CommentID
UserID
MovieID
Comment
Timestamp
So, what i wanna do is to group the comments on MovieID and save them into my object called Movie, where the MovieID is being saved in the MovieID post, and the Linq object is saved inside the ObservableCollection inside the Movie object.
public class Movie
{
#region Member Variables
public int MovieID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Uri Poster { get; set; }
public double Rating { get; set; }
public DateTime Timestamp { get; set; }
public ObservableCollection<MovieComment> Comments { get; set; } // Linq object: MovieComment
#endregion // Member Variables
}
I've come up with the following linq query where i get the MovieID, but i dont really know how i should proceed to get a hold of all the other data
public ObservableCollection<Movie> LoadMovieID(int _userID, int _limit)
{
ObservableCollection<Movie> movies = new ObservableCollection<Movie>();
var query = (from mc in db.MovieComment
where mc.UserID == _userID
orderby mc.Timestamp descending
group mc by mc.MovieID into movie
select new
{
MovieID = movie.Key,
}).Take(_limit);
foreach (var row in query)
{
Movie movie = new Movie();
movie.MovieID = row.MovieID;
// I want to get the following:
// movie.MovieComment = MovieComment-objects with the MovieID == row.MovieID
movies.Add(movie);
}
return movies;
}
Is this even possible in a single query? Thankful for all the help i can get
Well, you could try this:
var query = (from mc in db.MovieComment
where mc.UserID == _userID
orderby mc.Timestamp descending
group mc by mc.MovieID).Take(_limit);
That will give you a IGrouping<MovieComment, string> (or whatever your types are) which should let you get at all the comments without any extra work. It's certainly okay in terms of LINQ itself, but whether it will do what you want within LINQ to SQL, I'm not sure.

Categories