I have the following classes. I have a object var of Description class. I want to select Balance related to the Client provided in the var object using Linq to Sql or Lambda expression. How to join these tables to get the Balance from Account table?
public class Description
{
public int DescriptionID { get; set; }
// Attributes
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
}
public class Client
{
public int ClientID { get; set; }
// Attributes
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
public class User
{
public int UserID { get; set; }
// Attributes
}
public class Account
{
public int AccountID { get; set; }
[Required, Column("Balance"), Display(Name = "Account Balance")]
public double Balance { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
You could try this:
var balance = (from a in context.Accounts
join c in context.Clients on a.UserID equals c.UserID
where c.ClientID == yourDescriptionObject.ClientID
select a.Balance)
.SingleOrDefault();
Or - if you only have the DescriptionID:
var balance = (from a in context.Accounts
join c in context.Clients on a.UserID equals c.UserID
join d in context.Descriptions on c.ClientID equals d.ClientID
where d.DescriptionID == yourDescriptionID
select a.Balance)
.SingleOrDefault();
(Or FirstOrDefault() or ToList() or Sum()? Because your model would allow that clients/descriptions are related to multiple accounts ...)
Related
How to join multiple tables using group by. I have consulted some posts on stackoverflow, but it doesn't seem to work for me.
I have Model
public class Customer
{
public int ID { get; set; }
public string RadomID { get; set; }
public bool Active { get; set; }
}
public class RatingStore
{
public string RadomID { get; set; }
public string Content { get; set; }
}
public class Product
{
public int IDProduct { get; set; }
public string RadomID { get; set; }
}
This is how I count in CustomersController
public CustomersController(ApplicationDBContext context)
{
_context = context;
}
var qr = (from Customer c in _context.Customers
join o in _context.RatingStore on c.RadomID equals o.RadomID
join p in _context.Products on c.RadomID equals p.RadomID
where c.Active == true
group c by c.RadomID into g
select new
{
StoreId = g.Key,
CountRatingStore = g.Count(),
CountProdStore = g.Count(),
}).ToList();
However when I debug the results
CountRatingStore = g.Count() --> result: 2
CountProdStore = g.Count() --> result: 2
It has to be like this:
CountRatingStore = g.Count() --> result: 1
CountProdStore = g.Count() --> result: 2
Because of the data in my database:
Table Product:
Table RatingStore:
Table Customer:
Maybe my command is incorrect. How to get the correct result as I described above. Thank you
Update
public class ApplicationDBContext : DbContext
{
public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
{
}
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<RatingStore> RatingStore { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
}
I am trying to count the number of columns of Table Product and RatingStore with the same RandomID condition.
---> The problem I have not been able to solve. I ask for help from everyone.
I want to display the results of this SQL query in a WPF datagrid. My question how to run this query using EF6?
select c.*, count(o.id) from clients c
left join optics o
on o.client_id = c.id
where o.r_sph = 12 // 12 is a variable value
group by c.id
My Clients model:
public clients()
{
this.optics = new ObservableCollection<optics>();
}
public long id { get; set; }
public string name { get; set; }
public string phone { get; set; }
public Nullable<System.DateTime> date_of_birth { get; set; }
public System.DateTime inserted_at { get; set; }
public System.DateTime updated_at { get; set; }
public virtual ObservableCollection<optics> optics { get; set; }
And Optics model:
public long id { get; set; }
public Nullable<System.DateTime> at { get; set; }
public Nullable<decimal> r_sph { get; set; }
public Nullable<int> r_axs { get; set; }
public string notes { get; set; }
public Nullable<long> client_id { get; set; }
public System.DateTime inserted_at { get; set; }
public System.DateTime updated_at { get; set; }
public virtual clients clients { get; set; }
Update:
I use this code to filter the results:
public IQueryable < Multi.Model.clients > FilterClients(optisysEntities db, System.Linq.IQueryable < Multi.Model.clients > clients, ClientsFilter clientsFilter) {
if (!String.IsNullOrWhiteSpace(clientsFilter.Name))
clients = db.clients.Where(c => c.name.Contains(clientsFilter.Name));
if (!String.IsNullOrWhiteSpace(clientsFilter.Phone))
clients = clients.Where(u => u.phone.Contains(clientsFilter.Phone));
}
You will need to return a new object (unless you already have a model set up which includes the "Count" property). Something like this:
var query = (from c in context.Clients
join o in context.Optics
on c.id equals o.client_id
where o.r_sph == 12
group new { c, o } by new { c.Id }
into g
select new {Id = g.Key.id,
// other properties from "Client",
Count = g.Count()}
).ToList();
I have Models created through Entity Framework as:
public partial class Order
{
public Order()
{
this.OrderDetails = new HashSet<OrderDetail>();
}
public int OrderID { get; set; }
public string OrderNo { get; set; }
public System.DateTime OrderDate { get; set; }
public string Description { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Then another Details Table:
public partial class OrderDetail
{
public int OrderItemsID { get; set; }
public int OrderID { get; set; }
public string ItemName { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
public decimal TotalAmount { get; set; }
public virtual Order Order { get; set; }
}
To See the Master Detail Data I made MasterDetails model As:
public class OrderVM
{
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Description { get; set; }
public List<OrderDetail> OrderDetails {get;set;}
}
I'm trying to make a method that return a LIST with Join query results but
I'm receiving #Anonymous type error here is my Code:
public static List<OrderVM > mylist()
{
List<OrderVM> slist = new List<OrderVM>();
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new
{
O.OrderID,
O.OrderDate,
D.Quantity,
D.Rate
};
foreach(var myorders in myvalues)
{
slist.Add(myorders);
}
return slist;
}
}
I need a help that how I can I create a generic list with database fields
Create new class:
public class OrderDetailsModel
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
}
and return list of objects of this class from your method:
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new OrderDetailsModel
{
OrderId = O.OrderID,
OrderDate = O.OrderDate,
Quantity = D.Quantity,
Rate = D.Rate
};
return myvalues.ToList();
}
Database Models of my Application are:
public class Restaurant
{
public int Id { get; set; }
.........
}
public class Review
{
public int Id { get; set; }
public string ReviewTitle { get; set; }
public string ReviewContent { get; set; }
public int UserId { get; set; }
public int RestaurantId { get; set; }
}
public ReviewHelpful
{
public int Id { get; set; }
public int ReviewId { get; set; }
public bool IsHelpfull { get; set; }
}
public ReviewImage
{
public int Id { get; set; }
public string ImageLink { get; set; }
public int ReviewId { get; set; }
}
There is no navigation property in any table. In ReviewHelpful table, If user finds helpfull of this review than value is true otherwise false.
Now I want to create a view-model Like this:
public class ReviewViewModel
{
public int ReviewId { get; set; }
public int RestaurantId { get; set; }
public string ReviewTitle { get; set; }
public string ReviewContent { get; set; }
public int UserId { get; set; }
public int NumberOfHelpfull { get; set; }
public int NumberOfNotHelpfull { get; set; }
public List<string> ImagesLinks { get; set; }
}
For that reason, I want to write this kind of query :
var reviews = (from review in _foodTrackerContext.RestaurantReviews
join helpful in _foodTrackerContext.Helpfuls on review.Id equals helpful.ReviewId
join reviewPicture in _foodTrackerContext.ReviewPictures on review.Id equals reviewPicture.ReviewId
where review.ResturantId == 2
select new ReviewViewModel()
{
Id = review.Id,
RestaurantId = 2,
ReviewTitle = review.ReviewTitle,
ReviewContent = review.ReviewContent,
NumberOfHelpfull = .. ??,
NumberOfNotHelpfull = ... ??,
ImagesLinks = ... ???
}
I can not retrieve HelpfulYes, HelpfulNo, ImagesLinks with this query. What would be query for finding these variables?.
This query produces multiple rows for single review with each ReviewImage and each ReviewHelpful.
The query that ypu need to do is this one:
var model =
from review in ctx.Reviews
where review.RestaurantId == 2
join helpful in ctx.ReviewHelpfuls
on review.Id equals helpful.ReviewId into helpfuls
join image in ctx.ReviewImages
on review.Id equals image.ReviewId into images
select new RestaurantReviewViewModel
{
Id = review.Id,
RestaurantId = 2,
ReviewTitle = review.ReviewTitle,
ReviewContent = review.ReviewContent,
NumberOfHelpfull = helpfuls.Count(h => h.IsHelpfull),
NumberOfNotHelpfull = helpfuls.Count(h => !h.IsHelpfull),
ImagesLinks = (from image in images select image.ImageLink).ToList()
};
Please, note that when you do a one to manyh join you need to include an into to give a nameto the joined entities to be able to work on them.
I've used the dot syntax for selecting the count, but you could use the query syntax if you wanted. Over time, I've found dot synatx more natural.
NOTE: if you used navigation properties this would become much easier. Why are you not using them? With navigation properties you don't need to make the joins explicitly, as they are already available.
List<ReviewViewModel> listModel = new List<ReviewViewModel>();
context.dbRestaurant
.include("Review")
.include("Review.ReviewHelpful")
.include("Review.ReviewImage").ToList().ForEach((item) =>
{
ReviewViewModel model = new ReviewViewModel();
model.ID = item.ID
listModel.Add(model);
});
I have a model like the following:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public DateTime DateTime { get; set; }
public Customer Customer { get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public int Id { get; set; }
public Product Product { get; set; }
public int Price { get; set; }
public int Quantity { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
I am using this infrastructure.
My aggregate roots are Customer, Order, Product. I did not include the mappings here as they are straight forward.
var customers = unitOfWork.Customers.FindAll();
var orders = unitOfWork.Orders.FindAll();
var products = unitOfWork.Products.FindAll();
var query = ......
Using LINQ, how would you select all customers that have orders for products in the "Beverages" category?
All samples I have seen on the web are very basic queries nothing advanced.
i found http://msdn.microsoft.com/en-us/vbasic/bb737909
May be your query should look like:
from c in unitOfWork.Customers
join o in unitOfWork.Orders on o.Customer = c
join ol in unitOfWork.OrderLines on ol.Order = o
where ol.Product.Category.Name == "Beverages"
select c
And it is necessary to add all parent-object-properties
This might work or not:
from customer in customers
where customer.Orders.Any(
o => o.OrderLines.Any(l => l.Product.Category.Name == "Beverages")
select customer
(I'm assuming you forgot the relationship between Product and Category)