Joining query in Linq - sql

I have 2 tables. ProductOrder and Member.
ProductOrder: OrderId, MemberId, DateTimeUTC.
Member : MemberId, FName, LName.
I want to retun a list which content OrderId, Fname, LName, DateTimeUTC.
public List<ProductOrder> GetOrderDetails()
{
using (var db = new StoreEntities())
{
var query = (from pd in db.ProductOrder
join od in db.Member on pd.MemberId equals od.MemberId
orderby od.MemberId
select new
{
pd.OrderId,
od.FName,
od.LName,
pd.DateTimeUTC,
}).ToList();
return query;
}
}
But here some error occur.
Please help.

Your query returns a collection of anonymous type instances. It shouldn't be returned from as method.
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.
from Anonymous Types (C# Programming Guide)
Instead, you have to create new class to store your results:
public class OrderInfo
{
public int OrderId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public DateTimeUTC { get; set; }
}
change method declaration to return collection of OrderInfo:
public List<OrderInfo> GetOrderDetails()
and modify query to return a collection of these objects:
var query = (from pd in db.ProductOrder
join od in db.Member on pd.MemberId equals od.MemberId
orderby od.MemberId
select new OrderInfo
{
pd.OrderId,
od.FName,
od.LName,
pd.DateTimeUTC,
}).ToList();

Related

WindowsForms-EFCore SQL Exception Invalid Column Name

I have a two table products and categories. When I add a product to products, I get an error. I share the codes.
class Products
{
public int Id { get; set; }
public string Name { get; set; }
public float Price { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public Categories Category { get; set; }
}
With this method, I get the products. After I fill a datagridview. But I want to see categoryName instead of CategoryId. It works, I see the categoryName instead of CategoryId in datagridview.
public List<Products> GetProducts()
{
var products = context.Products.Include(x =>x.Category ).Select(m => new Products()
{
Id = m.Id,
Name = m.Name,
Price = m.Price,
Description = m.Description,
CategoryName=m.Category.Name
}).ToList();
return products;
}
After that I have an Add method
public void AddProduct(Products products )
{
context.Products.Add(products);
context.SaveChanges();
}
However, when I try to add a new product, I have an error.
The issue is that Category Name is not in the physical table, just your object. So when EF attempts to generate the SQL, it can't find a column called CategoryName.
Take a look at this question
Exclude Property on Update in Entity Framework

NHibernate QueryOver and selecting rows where a propery is an ILIST and the list count >= 1

I would like to select rows for which the property Items which is an IList has rows itself. In SQL its easy count >= 1 but in NHibernate it eludes me.
Tried many ways
public class Sale
{
private IList<Items> _items;
public Sale()
{
_items = new List<Item>();
}
public Guid SaleId { get; set; }
public string SaleNumber { get; set; }
public string Location { get; set; }
public DateTime? SaleDateTime { get; set; }
public IList<Item> Items => _items;
}
public class Item
{
public Guid ItemId { get; set; }
public string description { get; set; }
}
var testdata = _session.QueryOver<Sale>()
.Where(Restrictions.Ge(
Projections.Property<Sale>
(m => m.Items.Count), 1))
.ReadOnly()
.ListAsync();
Count is unrecognized
Technically if you did an inner join you wouldn't receive any Sale records back that do not have any Item records.
So as a really simple QueryOver you could do:
var sales = session.QueryOver<Sale>()
.Inner.JoinQueryOver(x => x.Items)
.Select(Projections.RootEntity())
.TransformUsing(Transformers.DistinctRootEntity)
.List();
This is the resulting SQL:
SELECT this_.SaleId as saleid1_1_0_,
this_.SaleNumber as salenumber2_1_0_,
this_.Location as location3_1_0_,
this_.SaleDateTime as saledatetime4_1_0_
FROM Sale this_
inner join Item item1_ on this_.SaleId=item1_.SaleId

linq query with a list in the where clause

I have a linq query written in the below format. Now when I am passing a consumerID it works fine and I am able to put it in the where clause. However when I try to pass a list of consumerIds, how can I put this in the where clause. I have looked through some solution online and they all use some other linq format which I dont want to use.
Please suggesest if I can have a list in the where clause, something similar to how we can have in clause in sql??
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
join con in db.D on cecr.ConsumerID equals con.ID
where con.ID.Contains(consumerIDs) && !ecew.Deleted
select new E
{
ConsumerID = con.ID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = ecew.Deleted
}).ToList();
return results;
}
Here is the dto class
public class E : ILzDto
{
public int ConsumerID { get; set; }
public int OrganizationID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Deleted { get; set; }
}
Change this:
where con.ID.Contains(consumerIDs)
to this:
where consumerIDs.Contains(con.ID)
This will check if the id of the items in the select statement are in the input list.

ASP.NET MVC 4 joining 2 tables in stored Procedure but giving only one table's data

I am new in ASP.NET MVC 4; Using DATABASE FIRST APPROACH. According to my question I am using SQL stored procedure to retrieve data to populate my jQgrid. But it is retrieving all BO tables data except OrgName which is coming from Org table(look in stored procedure). So What I do to get OrgName???
My Stored Procedure is as follows :
ALTER PROCEDURE [dbo].[GetBODetails]
AS
BEGIN
SELECT b.Id, b.OrgId, b.Code, b.Name, o.Name AS OrgName
FROM Org AS o INNER JOIN BO AS b ON o.Id = b.OrgId
END
Columns of BO table :
Id = GUID
Code = NVARCHAR(50)
Name = NVARCHAR(50)
OrgId = Foreign Key ref from Org table Id
Columns of BO table :
Id = GUID
Name = NVARCHAR(50)
Used this Procedure in my MVC project by doing "Add Function Import" from Model Browser window ;by referring this article Click here. While doing this I select Returns a collection of Entities is BO model.
Model generated of BO and Org are as follows :
BO.cs
public partial class BO
{
public System.Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public System.Guid OrgId { get; set; }
public virtual Org Org { get; set; }
}
Org.cs
public partial class Org
{
public Org()
{
this.BOes = new HashSet<BO>();
}
public System.Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<BO> BOes { get; set; }
}
Controller's code to execute Stored Procedure :
private iregEntities m_oDbCont = new iregEntities();
// GET: /BO/
public JsonResult BOGrid()
{
m_oDbCont.Configuration.ProxyCreationEnabled = false;
var BOList = m_oDbCont.GetBODetails().ToList(); // Executing stored procedure
var JsonBOList = new
{
rows = (
from BOData in BOList
select new
{
id = BOData.Id.ToString(),
cell = new string[] { BOData.OrgId.ToString(), BOData.Code, BOData.Name }
}).ToArray()
};
return Json(JsonBOList, JsonRequestBehavior.AllowGet); returning data into JSON format
}
protected override void Dispose(bool disposing)
{
m_oDbCont.Dispose();
base.Dispose(disposing);
}
While doing the function import, ask to create a new complex type instead of mapping the result to the BO entity. If you map to the BO entity, only this entity will be filled up with data, that's why Org is empty.
When mapping to a complex type, EF will automatically create a new class containing all the columns returned by the SP.
Mapping SP result to a specific entity is useful when the SP is returning that particular entity, it avoids creating useless complex types everytime you import an SP.

PetaPoco returning incorrect ID

I have the following model and methods:
[PetaPoco.TableName("TestStep")]
[PetaPoco.PrimaryKey("ID")]
public class TestStep
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public string Details { get; set; }
}
public IEnumerable<TestStep> GetById(int ID)
{
var db = new PetaPoco.Database("TestProcedureDB");
return db.Query<TestStep>(#"SELECT * FROM TESTSTEP TS
INNER JOIN TESTSTEPLINK L ON L.STEPID = TS.ID
WHERE L.TESTID = #0", ID);
}
When the POCO is populated, the ID property value is that of the ID column in the TESTSTEPLINK table. If I change the query to return SELECT TS.* then all is ok. Is this a bug or am I missing something?
PetaPoco will go through all your return columns and map them.
First it will map Id from the table TESTSTEP, then it finds Id again and so it overrides the previously set value.
If you are doing a join like this and only want specific information, you should either only specify the columns you want to return (otherwise you are bringing back more data than needed which is a performance issue)
or do as you did to fix it by using TS.* to ensure only the columns from the first table are mapped.