cannot convert from 'System.Collections.Generic.List<object>' to 'System.Collections.Generic.List<DAL.model>' - asp.net-web-api

I want to retrieve all determined columns from the model table as queryable
I write code blow it shows me
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
any help to solve this error with the best practice:**
public IQueryable<DAL.model> GetAllmodels()
{
var models = (from d in db.models
where (d.Model_Deleted == false)
select (
new
{
d.Model_ID,
d.Model_Name,
d.Model_Image
})).AsQueryable();
return models;
}

Instead of selecting anonymous object with new { .. } Try as below with new DAL.model() { ... }.
public IQueryable<DAL.model> GetAllmodels()
{
var models = (from d in db.models
where (d.Model_Deleted == false)
select (
new DAL.model()
{
Model_ID = d.Model_ID,
Model_Name = d.Model_Name,
Model_Image = d.Model_Image
})).AsQueryable();
return models;
}

Related

how to return multiple items from linq query

Hi I have a method which i am calling to get the list of email of users , i am returning that list and my calling method is using these emails , I want to get the program title as well to pass with the list how to achieve that.
public static List<string> GetAllStudents(int? year,int? program,int? module,int? block)
{
var res = (from s in std.Student_courses
join p in std.Programs
on s.Program_Id equals p.Id
join sc in std.Students
on s.Student_id equals sc.Student_Id
where s.Program_Id == program && s.Year_Id == year && s.Module_Id==module && s.Block_Id==block
select new
{
Email = sc.Student_Email,
Program=p.Program_Title
}).ToList();
List<string> EmailList = new List<string>();
foreach (var item in res)
{
EmailList.Add(item.Email);
}
return EmailList;
//var result = from userDistrict in std.Student_courses
// from district in std.Students
// where (userDistrict.Student_id == district.Student_Id)
// select district.Student_Email;
// return std.Student_courses.Where(x => x.Program_Id == program && x.Year_Id == year && x.Module_Id == module && x.Block_Id == block ).ToList();
}
Using new {} creates an anonymous type which cannot be passed to a method or returned out of the method scope (even if it's inside a list).
You are returning a list of string values. I recommend you change this to a list of a new class that contains both the email and the Program properties.
public class EmailInfo
{
public string Email { get; set; }
public string Program { get; set; }
}
You can then return this class from your method:
public static List<EmailInfo> GetAllStudents(int? year, int? program, int? module, int? block)
{
var results =
from s in std.Student_courses
join p in std.Programs on s.Program_Id equals p.Id
join sc in std.Students on s.Student_id equals sc.Student_Id
where s.Program_Id == program && s.Year_Id == year && s.Module_Id == module && s.Block_Id == block
select new EmailInfo
{
Email = sc.Student_Email,
Program = p.Program_Title
};
return results.ToList();
}
And use both values (as an example I've printed the values to the console):
var emails = GetAllStudents();
emails.ForEach(x => Console.WriteLine($"'{x.Email}', '{x.Program}'"));
This could print the following to the console:
'email1#domain.com', 'title 1'
'email2#domain.com', 'title 2'

How to: linq query

I am trying to get a record from database using linq but it keep return no record
it is very basic sql statment
select * where productid ='12553'
however the following code does not return any result. Please advise. thx you
private static IEnumerable<ProductModel> GetAllProduct(string productId)
{
using (var dc = new TestEntities())
{
var result = (from a in dc.Products
where a.productid == productId
select new ProductModel
{
ProductId = a.productid,
Name = a.ProductName
});
return result.Distinct().ToList();
}
}
You don't need projection here:
using (var dc = new TestEntities())
{
var result = from a in dc.Products
where a.productid == productId
select a;
return result.Distinct().ToList();
}

How to convert a string to decimal in a LINQ query

I have the following Linq statement:
var total = (from a in mobileChunk.Data select a.callCost).Sum();
callCost is a string. I need to convert it to a decimal. How is this done?
i would do something like this....
public static class Extenders
{
public static decimal ToDecimal(this string str)
{
// you can throw an exception or return a default value here
if ( string.IsNullOrEmpty(str) )
return someDefaultValue;
decimal d ;
// you could throw an exception or return a default value on failure
if ( !decimal.TryParse(str, out d ) )
return someDefaultValue;
return d;
}
}
now, in your linq.....
var total = = (from a in mobileChunk.Data select a.callCost.ToDecimal()).Sum();
Perhaps you can try this:
var total = (from a in mobileChunk.Data select decimal.Parse(a.callCost)).Sum();

EF single entity problem

I need to return a single instance of my viewmodel class from my repository in order to feed this into a strongly-typed view
In my repository, this works fine for a collection of viewmodel instances:
IEnumerable<PAWeb.Domain.Entities.Section> ISectionsRepository.GetSectionsByArea(int AreaId)
{
var _sections = from s in DataContext.Sections where s.AreaId == AreaId orderby s.Ordinal ascending select s;
return _sections.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
);
}
But when I attempt to obtain a single entity, like this:
public PAWeb.Domain.Entities.Section GetSection(int SectionId)
{
var _section = from s in DataContext.Sections where s.SectionId == SectionId select s;
return _section.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
);
}
I get
Error 1 Cannot implicitly convert type
'System.Linq.IQueryable<PAWeb.Domain.Entities.Section>' to
'PAWeb.Domain.Entities.Section'. An explicit conversion exists
(are you missing a cast?)"
This has got to be simple, but I'm new to c#, and I can't figure out the casting. I tried (PAWeb.Domain.Entities.Section) in various places, but no success. Can anyone help??
Your query is returning an IQueryable, which could have several items. For example, think of the difference between an Array or List of objects and a single object. It doesn't know how to convert the List to a single object, which one should it take? The first? The last?
You need to tell it specifically to only take one item.
e.g.
public PAWeb.Domain.Entities.Section GetSection(int SectionId)
{
var _section = from s in DataContext.Sections where s.SectionId == SectionId select s;
return _section.Select(x => new PAWeb.Domain.Entities.Section()
{
SectionId = x.SectionId,
Title = x.Title,
UrlTitle = x.UrlTitle,
NavTitle = x.NavTitle,
AreaId = x.AreaId,
Ordinal = x.Ordinal
}
).FirstOrDefault();
}
This will either return the first item, or null if there are no items that match your query. In your case that won't happen unless the table is empty since you don't have a where clause.

What wrong I am doing in IEnumerable(C#3.0)

If I write
var v = (from r in stock.ReplacementLog
select new
{
AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value
});
It is working fine...
But if I do
IEnumerable<StockAsset> v = (from r in stock.ReplacementLog
select new {
AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value });
I am getting error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
Then I did
IEnumerable<StockAsset> v =
(
from r in stock.ReplacementLog
select new
{
AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value
}).ToList<StockAsset>();
With the following bunch of errors:
Error 1 Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'
Error 2 'System.Collections.Generic.IEnumerable' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments
Then I tried with
IEnumerable<StockAsset> v1 =
(from r in stock.ReplacementLog
select new StockAsset
{
AssetId = stock.AssetId,
ReferDate= stock.ReferDate,
FactType = r.Key,
Value = r.Value
});
with the errors:
Error 1
'StockAsset' does not contain a definition for 'FactType'
**Error 2
'StockAsset' does not contain a definition for Value'**
The StockAsset Class is as under
public class StockAsset
{
public int AssetId { get; set; }
public DateTime ReferDate {get;set;}
public Dictionary<EnumFactorType, double> ReplacementLog { get; set; }
}
Need help.
Using C#3.0
Thanks
When you write
select new {
AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value }
You actually generate an anonymous type. You can't cast this anonymous type to a declared type.
If you want to create an object of the class you should do
select new StockAsset
{
AssetId = ..., // Maybe stock.AssetId
ReferDate = ..., // Maybe stock.ReferDate
ReplacementLog = ... // Maybe new Dictionary<string, short> { {r.Key, r.Value} };
}
When you write
select new { property = value }
you're creating an instance of a new anonymous type, whereas it looks like you want to actually be creating StockAssets, so you want
select new StockAsset { property = value }
My best guess is that you're trying to create a new StockAsset for each entry in another StockAsset's ReplacementLog. This new StockAsset is going to have a single entry in its ReplacementLog. Is this correct? If so, you could create a new constructor on StockAsset:
public StockAsset(int assetId, DateTime referDate,
EnumFactorType factorType, double value)
{
AssetId = assetId;
ReferDate = referDate;
ReplacementLog = new Dictionary<EnumFactorType, double>();
ReplacementLog[factorType] = value;
}
And then call that constructor inside of your LINQ.
IEnumerable<StockAsset> v = (from r in stock.ReplacementLog
select new StockAsset(stock.AssetId, stock.ReferDate, r.Key, r.Value));

Resources