I have a class which should take the query results from a database using a join.
My class is:
`
public class StepTwo
{
public int Id { get; set; }
public string Party { get; set; }
public string Currency { get; set; }
public string Account { get; set; }
public double? Amount { get; set; }
}
`
I have then created a method which will return the results:
public IEnumerable<StageTwo> StepTwo()
{
var queryJoin = (from inn in db.Input.Take(10)
join yacc in db.AccY on inn.Action equals yacc.Action
orderby inn.Id descending
select new
{
inn.Id,
inn.XParty,
inn.Curr,
yacc.Action,
inn.Amount
});
return queryJoin;
}
In other methods where I did not use a join, this worked fine but now it is not working. I have the error message on the return queryJoin; stating:
`
Cannot implicitly convert type 'System.Linq.IQueryable<<anonymous type: int Id, string XParty, string Curr, string YAction, double? Amount>>' to '
System.Collections.Generic.IEnumerable<Project.StepTwo>'. An explicit conversion exists (are you missing a cast?)`
I know the class names are a bit different from the database names but I have tried to change them to match. Based on the error above, I assume it's something else.
Any advise would be appreciated, thank you.
Your error message is telling you that queryJoin is an anonymous type, but you are trying to force it to be an IEnumerable<StageTwo>, and C# can't make that conversion.
The reason queryJoin is an anonymous type is because you've not defined it in your linq query. So to fix it, instead of this:
select new
{
inn.Id,
inn.XParty,
inn.Curr,
yacc.Action,
inn.Amount
});
You'd want this:
select new StepTwo
{
Id = inn.Id,
Party = inn.XParty,
Currency = inn.Curr,
Account = yacc.Action,
Amount = inn.Amount
});
Related
I have a 'GetTransactions' method that returns an object of type:
IList<ApplicationTransaction>
Where this is an ApplicationTransaction:
public partial class ApplicationTransaction
{
public int TransactionId { get; set; }
public int ApplicationId { get; set; }
public string Event { get; set; }
public System.DateTime CreatedOn { get; set; }
public virtual Application Application { get; set; }
}
How do I convert this LINQ query:
return (from t in GetTransactions().OfType<ApplicationTransaction>()
where t.Event == transactionType.ToString()
select t).FirstOrDefault();
Into fluent syntax?
This doesn't work - what am I not understanding?
return GetTransactions().OfType<ApplicationTransaction>().Where(t.Event == transactionType.ToString().FirstOrDefault();
You need parameter to a lambda in your where statement:
return GetTransactions()
.OfType<ApplicationTransaction>()
.Where(t => t.Event == transactionType.ToString())
.FirstOrDefault();
(Notice t => part where defines a new expression scope instead of directly trying to access a variable "t")
You don't need a separate select if you're selecting the whole entity.
I also suggest using the multiline layout I used in the answer to understand the query better and catch potential problems like the missing parenthesis issue #nvoigt mentioned.
I am using .NET 4.6 and I am trying to create a specific list from a generic one. Code(the generic list):`
var clients = (from a in accounts
group j by new
{
a.Code,
a.Name,
a.AddressLine1,
a.Postcode,
a.City,
}
into g
select new
{
g.Key.Code,
g.Key.Name,
g.Key.AddressLine1,
g.Key.PowerTools,
g.Key.Internetportal,
g.Key.Huisvestingsplanning,
g.Key.Werkplanning,
g.Key.Vervoersplanning
}).ToList();
The specific List(Customer.cs):
struct Customer
{
public string Code { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public double PowerTools { get; set; }
public double Internetportal { get; set; }
public double Huisvestingsplanning { get; set; }
public double Werkplanning { get; set; }
public double Vervoersplanning { get; set; }
}
Conversion:
customers = clients.Cast<List<object>>().Select(x => new Customer(){
Code = (string)x[0],
Name = (string)x[1],
Address = (string)x[2],
PowerTools = (double)x[3],
Internetportal = (double)x[4],
Huisvestingsplanning = (double)x[5],
Werkplanning = (double)x[6],
Vervoersplanning = (double)x[7]}).ToList();
The error this conversion throws:
Unable to cast object of type '<>f__AnonymousType68 [System.String,System.String,System.String,System.Double,System.Double,System.Double,System.Double,System.Double]' to type 'System.Collections.Generic.List1[System.Object]'.
Thanks
Your code appears to be trying to convert some object into a list of its properties - this isn't going to work, C# isn't JavaScript. It's doable, but completely unnecessary.
What you really need is to just use the anonymous type in the way it's meant to be used:
clients.Select(x => new Customer { Code = x.Code, Name = x.Name, ... }).ToList();
Depending on the actual LINQ provider you're using, it might even be possible to skip the middle man and select directly into your own type - consult the documentation.
Also, just for clarity - both of those lists are generic. The difference is that the first one is a generic list of an anonymous type, while the second one is a generic list of a named type.
I am trying to read an XML file, but getting type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select' error as a result of the following query:
List<Data> dogs = (from q in doc.Descendants("dog")
where (string)q.Attribute("name") == dogName
select new Data
{
name = q.Attribute("name").Value,
breed = q.Element("breed").Value,
sex = q.Element("sex").Value
}.ToList<Data>);
Data class:
public class Data
{
public string name { get; set; }
public string breed { get; set; }
public string sex { get; set; }
public List<string> dogs { get; set; }
}
The problem is with your closing parenthesis - you've got it at the end of the ToList() call, when you meant to put it at the end of the object initializer. Also, you're not actually calling the method - you're just specifying a method group. Finally, you can let type inference work out the type argument for you:
List<Data> dogs = (from q in doc.Descendants("dog")
where (string)q.Attribute("name") == dogName
select new Data
{
name = q.Attribute("name").Value,
breed = q.Element("breed").Value,
sex = q.Element("sex").Value
}).ToList();
I am having trouble accessing a property from a joined table, using EF Code First. Here is my query in my home controller:
var pcs = from h in db.Hardwares
join hwt in db.HardwareTypes
on h.HardwareTypeId equals hwt.Id
where h.HardwareType.HType == "PC"
select new { Hardware = h, HardwareType = hwt };
ViewBag.Pcs = pcs.ToList();
Here is my HardwareTypes class:
public class HardwareType
{
public int Id { get; set; }
//[Required]
//[StringLength(128)]
public string HType { get; set; }
}
Here is my Hardware class:
public class Hardware
{
public int Id { get; set; }
public int HardwareTypeId { get; set;}
public virtual HardwareType HardwareType { get; set; }
}
How do I change my LINQ query so HType is in my ViewBag? The database seems to be generating correctly, it's just I can't seem to access HType. I get an error 'object' does not contain a definition for 'HType'
Ok, time for a full reset. Based on the chat, I want you to try the following:
1) Keep your original LINQ query, but don't make it an anonymous type. Create another object type that will have a Hardware and a HardwareType property in it. This will make Pcs (as well as ViewBag.Pcs) a List of that particular type.
2) Put the following foreach loop in your View code:
foreach (var item in ViewBag.Pcs as List<YourTypeName>)
{
var htype = item.HardwareType.HType;
}
And if you don't want to do some lazy loading each time through the loop, you can do the following in the controller to just load up the entities right away:
var hardwareTypes = pcs.Select(p => p.HardwareType).ToList();
Let me know if that works.
I'm trying to do something that should be real simple but I'm getting errors I don't know how to correct. Also, I don't even know if I'm doing things the "correct" way.
I have 3 entities. My first entity is called Bill and it's my main one. The other two are Repeat and Type. Bill has foreign keys (i.e. TypeId) which point to their respective primary keys. Both Type and Repeat are similar. They have their Id and description.
What I'm trying to do with EF and LINQ to Entity: Get all bills with all the properties of Bill but instead of the TypeId, I want TypeDesc.
This is an N tier Solution with 3 projects
Thus far I have my data layer I call Model, business layer I call BLL and my presentation later I call GUI.
namespace BillApp.Model
{
public class BillModel
{
public List<BillType> GetAllBills()
{
using (BillsEntities be = new BillsEntities())
{
var results = from o in be.Bills
.Include("Type")
.Include("Repeat")
select new
{
BillId = o.BillId,
Name = o.Name,
URL = o.URL,
PaymentAmount = o.PaymentAmount,
Balance = o.Balance,
DueDate = o.DueDate,
TypeDesc = o.Type.TypeDesc,
RepeatDesc = o.Repeat.RepeatDesc,
Username = o.UserName
};
return results.ToList();
}
}
}
public class BillType
{
#region Properties
public int BillId { get; set; }
public string Name { get; set; }
public string URL { get; set; }
public decimal PaymentAmount { get; set; }
public decimal Balance { get; set; }
public DateTime DueDate { get; set; }
public string TypeDesc { get; set; }
public string RepeatDesc { get; set; }
public string Username { get; set; }
#endregion
}
}
results returns an error Cannot implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Collections.Generic.List<BillApp.Model.BillType>
Next I try and pass the object to my BLL with this code.
namespace BillApp.BLL
{
public class BillBLL
{
public List<BillType> GetAllBills()
{
BillModel b = new BillModel();
return b.GetAllBills();
}
}
}
But BillType has an error:The type or namespace name 'BillType' could not be found (are you missing a using directive or an assembly reference?)
What am I missing? What can I do better?
I think the error messages are pretty clear: results is of type IQueryable<T> and you're trying to return a List<T>. To return a list instead, you can use the ToList method. You'll also need to create instances of BillType instead of anonymous objects, so that it conforms to the List<BillType> return type. Your GetAllBills method would look like this:
public List<BillType> GetAllBills()
{
using (BillsEntities be = new BillsEntities())
{
var results = from o in be.Bills
.Include("Type")
.Include("Repeat")
select new BillType
{
BillId = o.BillId,
Name = o.Name,
URL = o.URL,
PaymentAmount = o.PaymentAmount,
Balance = o.Balance,
DueDate = o.DueDate,
TypeDesc = o.Type.TypeDesc,
RepeatDesc = o.Repeat.RepeatDesc,
Username = o.UserName
};
return results.ToList();
}
}
For the second error you're probably just missing a using directive to have access to your BillType type which is in a different namespace. You'd have this line at the top of the file:
using BillApp.Model;