return LINQ to list<entity>? - c#

List<PersonsInChargeEntity> picList = new List<PersonsInChargeEntity>();
List<ClientEntity> clientList = new List<ClientEntity>();
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new { ClientNumber = pic.ClientNumber, CompanyName = client.CompanyNameFull, AICGroupID = pic.AICStaffGroupID, RPStaffID = pic.RPStaffID, MPStaffID = pic.MPStaffID, CSPStaffID = pic.CSPStaffID, EQCRStaffID = pic.EQCRStaffID }).ToList<PicList>();
How can i convert my returnList to a List< entity>? below is my class for the entity.
public class PicList
{
int _ClientNumber = 0;
string _CompanyName = "";
int _AICGroupID = 0;
int _RPStaffID = 0;
int _MPStaffID = 0;
int _CSPStaffID = 0;
int _EQCRStaffID = 0;
public PicList()
{
}
public PicList(int ClientNumber, string CompanyName, int AICGroupID, int RPStaffID, int MPStaffID, int CSPStaffID, int EQCRStaffID)
{
_ClientNumber = ClientNumber;
_CompanyName = CompanyName;
_AICGroupID = AICGroupID;
_RPStaffID = RPStaffID;
_MPStaffID = MPStaffID;
_CSPStaffID = CSPStaffID;
_EQCRStaffID = EQCRStaffID;
}
public int ClientNumber
{
get { return _ClientNumber; }
set { _ClientNumber = value; }
}
public string CompanyName
{
get { return _CompanyName; }
set { _CompanyName = value.Trim(); }
}
public int AICGroupID
{
get { return _AICGroupID; }
set { _AICGroupID = value; }
}
public int RPStaffID
{
get { return _RPStaffID; }
set { _RPStaffID = value; }
}
public int MPStaffID
{
get { return _MPStaffID; }
set { _MPStaffID = value; }
}
public int CSPStaffID
{
get { return _CSPStaffID; }
set { _CSPStaffID = value; }
}
public int EQCRStaffID
{
get { return _EQCRStaffID; }
set { _EQCRStaffID = value; }
}
}

From my understanding of your problem, you require the result of the query to be a List<PicList>. To accomplish this, you need to select an instance of the concrete PicList type within your LINQ query rather than of an anonymous type. C# doesn't normally support duck-typing (with some exceptions); in particular, it's not possible to cast one type to another just because the two types happen to have similar property declarations.
I also observe that PicList has a public parameterless constructor, and that all the properties have public setters. So this should work fine:
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList // no longer an anonymous type
{
ClientNumber = pic.ClientNumber,
CompanyName = client.CompanyNameFull,
AICGroupID = pic.AICStaffGroupID,
RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID,
CSPStaffID = pic.CSPStaffID,
EQCRStaffID = pic.EQCRStaffID
}).ToList();
//ToList<PicList>() is fine but redundant: the generic type argument is inferred.

you are creating an anonymous type here, which can't be casted like you've tried.
try something like:
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList
{
ClientNumber = pic.ClientNumber,
CompanyName = pic.CompanyNameFull,
AICGroupID = pic.AICStaffGroupID,
RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID,
CSPStaffID = pic.CSPStaffID,
EQCRStaffID = pic.EQCRStaffID
})/*.ToList()*/;

personList = picp.GetPersonsInChargeList(); // got 6000++ records
clientList = (List<ClientEntity>)cp.GetClientList(); // got 5000 ++ records after step thru
//PicList sdf;
var returnList = (from PersonsInChargeEntity pic in personList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList { ClientNumber = pic.ClientNumber, CompanyName = client.CompanyNameFull, AICGroupID = pic.AICStaffGroupID, RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID, CSPStaffID = pic.CSPStaffID, EQCRStaffID = pic.EQCRStaffID }).ToList();
but returnList doesnt have any records.

Hmmm, You can do it by very basic method linke this
List<ClientEntity> clientList = new List<ClientEntity>();
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select pic ;
foreach(var item in pic)
{
ClientEntity obj = new ClientEntity();
obj.ClientNumber = item.ClientNumber
......
......
clientList.add(obj);
}
return clientlist;
I hope this will run for you as well

Related

The specified type member 'TimeBandDescription' is not supported in LINQ to Entities

I have code that looks something like this bug getting error: the specified type member 'TimeBandDescription' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. How do I make this AsEnuermable?
public partial class TimeBand
{
public TimeBand()
{
}
public int Id { get; set; }
public string Name { get; set; }
public long From { get; set; }
public long To { get; set; }
[NotMapped]
public string TimeBandDescription => $"{Name} ({TicksToHhMmFormat(From)} - {TicksToHhMmFormat(To)})";
private static string TicksToHhMmFormat(long ticks)
{
if (ticks == long.MaxValue)
{
return "Max";
}
var timeSpan = new TimeSpan(ticks);
return $"{(int)timeSpan.TotalHours}{timeSpan.ToString(#"\:mm")}";
}
}
public class SuplierService : ISuplierService
{
public SupplierInfoModel GetSupplierList(int supplierId)
{
var query = (from s in suppliers
join tb in TimeBands on s.fkTimeBandId equals tb.Id
where s.supplierId == supplierId
select new SupplierInfoModel
{
SupplierId = supplierId,
SupplierEmail = s.Email,
Phone = s.Phone,
Fax = s.Fax,
TimeBandDescription = tb.TimeBandDescription,
I have a working solution but not the prettiest.
join tb in TimeBands on s.fkTimeBandId equals tb.Id
from tband in timeband.DefaultIfEmpty()
var Results = (from s in suppliers
join tb in TimeBands on s.fkTimeBandId equals tb.Id
where s.supplierId == supplierId
select new
{
TimeBand = tband,
Supplier = new HotelInfoModel
{
SupplierId = supplierId,
SupplierEmail = s.Email,
Phone = s.Phone,
Fax = s.Fax,
//TimeBandDescription = tb.TimeBandDescription, // no longer needed
. . .
}
}).ToList();
foreach (var result in Results)
{
result.Supplier.TimeBandDescription = result.TimeBand?.TimeBandDescription ?? "No Time Band Desc";
}
var suppliers = Results.Select(s => s.Supplier).ToList();

How to retrieve data from dynamic table in mvc

I'm writing new api call for my android app, I want to retrieve data from dynamic table, I mean when user select "A" button from Andriod I want to retrieve data from "A" table and if "B" is click , retrieve data from "B" table. Someone help me to find the possible solution.
I want to replace with variable for "JBCTNRITEMs" from entities.JBCTNRITEMs (table-name)
var query = (from jbct in entities.JBCTNRITEMs
where jbid.Contains(jbct.jbid.ToString()) && boxid.Contains(jbct.TrackingNo.ToString())
select jbct).ToArray();
int id = 0;
if (query.Length > 0)
{
id = (query[0].id);
}
return id;
Here are the two different possibilities as an example
if (module.ToLower() == "module-a")
{
var imageinfo = (from jb in entities.TableA.AsEnumerable()
where scanID.Contains(jb.aid.ToString())
select jb).ToArray();
InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "AIMAGE");
}
else if (module.ToLower() == "module-b")
{
var imageinfo = (from jb in entities.TableB.AsEnumerable()
where scanID.Contains(jb.bid.ToString())
select jb).ToArray();
InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "BIMAGE");
}
Here, query stores what you are you trying to select. As long as you are trying to select same type or same anonymous type, it will work.
Here is a simple example:
class Test1
{
public int ID { get; set; }
public string Name { get; set; }
}
class Test2
{
public int ID { get; set; }
public string Name { get; set; }
}
var test1Lst = new List<Test1>
{
new Test1() { ID = 1, Name = "Jitendra" },
new Test1() { ID = 2, Name = "Jahnavi" }
};
var test2Lst = new List<Test2>
{
new Test2() { ID = 1, Name = "Aaditri" },
new Test2() { ID = 2, Name = "Pankaj" }
};
var test = false;
var query = test ? (from t in test1Lst select new { ID = t.ID, Name = t.Name }) : (from t in test2Lst select new { ID = t.ID, Name = t.Name });
// Put whatever condition you want to put here
query = query.Where(x => x.ID == 1);
foreach(var t1 in query)
{
Console.WriteLine(t1.ID + " " + t1.Name);
}
I guess in this case I would suggest to use a generic method :
private T GetMeTheFirstEntry<T>(Expression<Func<T, bool>> filter) where T : class
{
return entities.GetTable<T>().FirstOrDefault(filter);
}
The GetTable will allow you to interchange the tableA and tableB. You would call it the following way:
TableA tableA_entity = GetMeTheFirstEntry<TableA>(jb => scanID.Contains(jb.aid.ToString()));
TableB tableB_entity = GetMeTheFirstEntry<TableB>(jb => scanID.Contains(jb.bid.ToString()));
If the filtering was successfull, then the retrieved object will not be null and you can use it:
int a_id = tableA_entity.aid;

How to map child objects to parent from Linq

I want to to make a list of the object MyProduct the problem is when i map the child objects to the parent object
My code looks like this
ShopDatabaseEntities db = new ShopDatabaseEntities();
var Result1 = (from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
Products.ProductName,
Products.ProductPrice,
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId
}).ToList();
List<MyProduct> lii = new List<MyProduct>();
foreach (var item in Result1)
{
MyProduct pp = new MyProduct();
pp = (from c in Result1
select new MyProduct { Name = item.ProductName }).First();
MyProperty e = new MyProperty();
e.PropertyName = item.PropertyName;
e.PropertyValue = item.PropertyValue;
pp.pros.Add(e);
lii.Add(pp);
}
It seems to me that this is more what you want:
var query =
from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId,
Products.ProductName,
Products.ProductPrice
};
List<MyProduct> lii =
query
.ToArray()
.GroupBy(x => new
{
x.ProductName,
x.ProductPrice
}, x => new
{
x.PropertyValue,
x.PropertyName,
x.PropertyId
})
.Select(x => new MyProduct()
{
Name = x.Key.ProductName,
pros = x
.Select(y => new MyProperty()
{
PropertyName = y.PropertyName,
PropertyValue = y.PropertyValue,
})
.ToList()
})
.ToList();
BTW, this is the code that you should have included in your question to make answering much easier:
public class ShopDatabaseEntities
{
public List<MyProduct> Products = new List<MyProduct>();
public List<MyProductProperty> ProductProperties = new List<MyProductProperty>();
public List<MyProperty> Properties = new List<MyProperty>();
}
public class MyProduct
{
public int ProductId;
public string Name;
public string ProductName;
public decimal ProductPrice;
public List<MyProperty> pros = new List<MyProperty>();
}
public class MyProductProperty
{
public int ProductId;
public int PropertyId;
public double PropertyValue;
}
public class MyProperty
{
public int PropertyId;
public string PropertyName;
public double PropertyValue;
}
Type defs help immensely.

Cannot implicitly convert type 'System.Collections.Generic.List error

Does any know why I am getting this error when trying to edit something in the database through the ForestLogisticBEAN class?
Cannot implicitly convert type
'System.Collections.Generic.List to
'System.Linq.IQueryable'.
An explicit conversion exists (are you missing a cast?)
Here is the integration layer:
public void EditParcelDetail(ForestLogisticBEAN parcel){
IQueryable<ForestLogisticBEAN> _ForestLogisticsBeans;
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new {order.DeliveryDate, order.OrderDate, tracking.Status} ).ToList();
}
Here is the ForestLogisticBEAN class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForestLogistic.Data.BEANS
{
public class ForestLogisticBEAN
{
public int TrackingId { get; set; }
public int OrderId { get; set; }
public bool Status { get; set; }
public DateTime OrderDate { get; set; }
public DateTime DeliveryDate { get; set; }
public ForestLogisticBEAN() { }
}
}
UPDATE:
I changed it to List instead of IQueryable but now it is throwing this error instead
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[ForestLogistics.Data.BEANS.ForestLogisticBEAN]',
but this dictionary requires a model item of type
'ForestLogistics.Data.Order'.
Here is the new integration layer:
public void EditParcelDetail(ForestLogisticBEAN parcel)
{
List<ForestLogisticBEAN> _ForestLogisticsBeans;
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new ForestLogisticBEAN {
DeliveryDate = parcel.DeliveryDate,
OrderDate = parcel.OrderDate,
Status = parcel.Status
});
_context.SaveChanges();
}
The aim is to be able to combine the order and the tracking table with the bean class
Enumerable.ToList returns a List<T> which implements IEnumerable<T> and not IQueryable<T>. So you cannot assign it to the IQueryable<ForestLogisticBEAN> variable.
So why don't you declare it as list or IEnumerable?
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
You also have to create instances of ForestLogisticBEAN instead of the anyonymous type that you're selecting. For example:
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new ForestLogisticBEAN {
Status = tracking.Status,
OrderDate = order.OrderDate,
DeliveryDate = order.DeliveryDate
}).ToList();
It's clear.
Define:
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
or
List<ForestLogisticBEAN> _ForestLogisticsBeans;
Why you define _ForestLogisticsBeans as IQueryable<ForestLogisticBEAN>? You have defined it as IQueryable and you are assigning List It always give you error.
try var _ForestLogisticsBeans = (from order in _context.Orders....
Or use
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
Or
List<ForestLogisticBEAN> _ForestLogisticsBeans;
Project in C# and Angular 2+
I am sure this would give result and this could be helpful to others while returning value i get
'System.Collections.Generic.List' to 'System.Collections.Generic.List'
my code is:
List<Ticket> objTicket = new List<Ticket>();
objTicket = ticketRepository.GetAllData().ToList();
List<AccountType> ListAccounType = new List<AccountType>();
ListAccounType = accountTypeRepository.GetAllData().ToList();
List<AccountTransaction> ListAccount = new List<AccountTransaction>();
ListAccount = accountTranastionRepository.GetAllData().ToList();
List<AccountTransactionValue> ListAccountTransactionValue = new List<AccountTransactionValue>();
ListAccountTransactionValue = accountTransactionValueRepository.GetAllData().ToList().Where(o => o.Date >= FromDate && o.Date <= ToDate).ToList();
var ListAccountTransaction = from v in ListAccountTransactionValue
join atr in objTicket on v.AccountTransactionId equals atr.Id
join a in ListAccount on v.AccountId equals a.Id
select new { v.Id, Name = a.Name, v.AccountTransactionId, VoucherNo = atr.Name.Substring(atr.Name.IndexOf("[")), AccountTransactionType = atr.Name.Substring(0, atr.Name.IndexOf("[")), atr.Date, SourceAccountTypeId = atr.Name, Description = atr.CompanyCode, DebitAmount = v.Debit, CreditAmount = v.Credit, atr.DepartmentId };
var ListScreenTicketType = ListAccountTransaction.Select(o => new { o.Id }).Distinct().ToList();
AccountTransactionDocument objAccountTransactionDocument = new AccountTransactionDocument();
if (objAccountTransactionDocument != null)
{
AccountTransactionType objAccountTransactionType = new AccountTransactionType();
}
List<ScreenTicket> listScreenTicket = new List<ScreenTicket>();
foreach (var accounttransaction in ListScreenTicketType)
{
var objaccounttransaction = ListAccountTransaction.Where(o => o.Id == accounttransaction.Id).FirstOrDefault();
ScreenTicket objScreenTicket = new ScreenTicket();
objScreenTicket.Id = accounttransaction.Id;
objScreenTicket.Name = objaccounttransaction.Date.ToShortDateString();
objScreenTicket.Note = objaccounttransaction.Name;
var dataBytes = objaccounttransaction.Name;
if (dataBytes != null)
{
objScreenTicket.IsActive = true;
}
else
{
objScreenTicket.IsActive = false;
}
var objscreens = ListAccountTransaction.Where(o => o.Name == objaccounttransaction.Name);
List<PaymentHistory> listPaymentHistory = new List<PaymentHistory>();
foreach (var screenvalue in objscreens)
{
PaymentHistory objPaymentHistory = new PaymentHistory();
objPaymentHistory.Id = screenvalue.Id;
objPaymentHistory.AmountPaid = screenvalue.CreditAmount;
objPaymentHistory.Id = screenvalue.Id;
listPaymentHistory.Add(objPaymentHistory);
}
objScreenTicket.PaymentHistory = listPaymentHistory;
listScreenTicket.Add(objScreenTicket);
}
return listScreenTicket;
}

ExpandoObject with Select Clause

I have to populate below class in Linq Query
public class Emp
{
public string name {get; set;}
public dynamic Obj { get; set; }
public Emp()
{
Obj = new ExpandoObject();
}
}
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = d.DOB,
Obj.BirthPlace = d.BirthPlace
}).ToList();
}
OR
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = new ExpandoObject { DOB = d.DOB, BirthPlace = d.BirthPlace } }).ToList();
}
it doesn't allow me to assign properties dynamically like above, Can anyone please help me how to achieve this?
Try this way:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
It is very similar to #gowansg answer, but without new keyword. It is just setting of values of properties. If we will try to get Type of Obj we will recieve System.Dynamic.ExpandoObject. With new keyword it will be some anonymous type.
respectively, such constructions like:
emp[0].Obj.OtherProperty = 1;
will fail in case of using anonymous type.
You were close in your second example, you just need to set Obj equal to a new anonymous object instead of a new ExpandoObject:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = new { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();

Categories