NotMapped property is not supported in Linq? - c#

I have added RunCount property in class and called in function as below.
public class ItemsDataObject
{
[Key]
[Column("ID")]
public string Id{ get; set; }
.
.
.
[NotMapped]
public int RunCount { get; set; }
}
public static List<ItemsDataObject> GetAllItemsWithPaging(int startingPageIndex, int pageSize, string orderColumn, string orderDir)
{
using (var ctx = new OracleDbContext())
{
List<ItemsDataObject> list = new List<ItemsDataObject>();
var v = (from a in ctx.Items select a);
v = v.OrderBy(orderColumn + " " + orderDir);
list = v.Skip(startingPageIndex).Take(pageSize).ToList();
return list;
}
}
There are large data in list so i need to firstly sort items and get 10 rows(pagesize) and then .ToList().
But i am getting System.NotSupportedException error. How can i fix the issue?
The specified type member 'RunCount' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

you can use
var v = from a in ctx.Items
orderby a.orderColumn ,a.orderDir;
list = v.Skip(startingPageIndex).Take(pageSize).ToList();

Related

Match 2 property of any object in local list using Linq

public class OrderItem
{
public int OrderID { get; set; }
public int ProductionID { get; set; }
}
public class InventoryItem
{
public int InventoryItemID{ get; set; }
public int OrderID { get; set; }
public int ProductionID { get; set; }
public bool Created { get; set; }
public bool Deleted { get; set; }
}
Using these example objects,
I have a local list of orderItems and want to query inventory items where OrderID and ProductionID matches on both properties any of my list of Order Items
I tried linq query below but I am getting an error
Query I am trying:
var results = await db.InventoryItems.Where(d =>
listOfOrderItems.Any(o => o.OrderID == d.OrderID && !d.DeleteFlag && d.ProductionId == o.ProductionItemId))
.Select(t => t.InventoryItemID).ToListAsync();
Exception thrown: 'System.NotSupportedException' in EntityFramework.SqlServer.dll
EDIT
i am being referred to this question:Using Linq to Sql asynchronously with new async/await
But my question is not about async await, it is about the matching 2 properties using the .any on my list
Try this:
var localIdPairs = listOfOrderItems.Select(x => x.OrderId + "-" + x.ProductionItemId).ToList();
var results = await db.InventoryItems
.Where(d => !d.DeleteFlag &&
localIdPairs.Contains(d.OrderId + "-" + d.ProductionItemId))
.Select(t => t.InventoryItemID).ToListAsync();
Looking further into the error I found this error:
Only primitive types or enumeration types are supported in this context.
My collection listOfOrderItems was of type List, changing it to IEnumerable fixed my problem

Linq Results into IEnumerable in ViewModel in ASP.NET MVC Controller

I am trying to put my linq query results into view model but I keep getting an error. Linq query returns multiple rating results. I would like to put these multiple rating results in an IEnumerable.
Error: Cannot implicitly convert type Models.CustomerRating' to 'System.Collections.Generic.IEnumerable<Models.CustomerRating>'. An explicit conversion exists (are you missing a cast?)
Linq query
var data = from profile in _context.Customers
join rating in _context.CustomerRating
on profile.strUserID equals rating.strUserID into rt
from subrating in rt.DefaultIfEmpty()
where profile.strUserID == UserId
select new { p = profile, r = subrating };
My view model:
public class ServiceProvider
{
public CustomerProfile Customer { get; set; }
public IEnumerable<CustomerProfile> CustomerProfiles { get; set; }
public CustomerServices CustomerServices { get; set; }
public FilterServicesViewModel FilterServices { get; set; }
public CustomerRating Rating { get; set; }
public IEnumerable<CustomerRating> CustomerRating { get; set; }
}
I would like to the results of profile to be added to Customer and subrating to CustomerRating IEnumerable.
I have tried the following but I get an error:
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
serviceProviderViewModel.CustomerRating = v.r;
}
Create a new list and loop through your linq query results and add it to that list
List<CustomerRating> RatingList = new List<CustomerRating>();
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
RatingList.Add(v.r);
}
serviceProviderViewModel.CustomerRating = RatingList;

Return NotMapped property in LINQ

I have one entity which is used in Entity Framework Code First.
public class MyEntity
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<string> ListOfValues
{
get
{
return StringsAsStrings?.Split(';').ToList();
}
set
{
StringsAsStrings = value.Count > 0 ? String.Join(";", value) : null;
}
}
[Column("ListOfValues")]
private string StringsAsStrings { get; set; }
public int RelationId { get; set; }
}
Here I am giving values as List to public and that should be stored as semicolon(;) separated string as in the table.
As this is specific to this data model, I specified StringsAsStrings as private and created a Convention to include in the migraion. All these are fine.
Now my scenario is to select the collection using LINQ. Please check the following linq query i used;
var items = from A in MyContext.MyEntities.Where(x => x.RelationId == paramId)
select new
{
Id = A.Id,
Name = A.Name,
ListOfValues = A.ListOfValues,
};
var result = items.ToList();
Here I got following error
The specified type member 'ListOfValues' is not supported in LINQ to
Entities. Only initializers, entity members, and entity navigation
properties are supported.
Ok fine. EF didn't support NotMapped properties. So for the work around i just changed private StringsAsStrings to public StringsAsStrings. Then changed the linq like below;
var items = from A in MyContext.MyEntities.Where(x => x.RelationId== paramId)
select new
{
Id = A.Id,
Name = A.Name,
ListOfValues = A.StringsAsStrings.Split(';').ToList(),
};
var s = items.ToList();
Now i got the following error;
LINQ to Entities does not recognize the method 'System.String[]
Split(Char[])' method, and this method cannot be translated into a
store expression.
Please help to solve this case.
Also help me if any other work around for this to avoid changing private to public property.

How can I extract data from a list of parent objects with children?

If I have a list inside a class inside of a list where the classes are defined like so:
class Class1
{
public int Id { get; set; }
public List<Class2> Class2s { get; set; }
}
class Class2
{
public string Name { get; set; }
public string Value { get; set; }
}
I can create a list of a class of type Result where Result is:
class Result
{
public int Class1Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Note that the Result class contains values from Class1 and Class2.
Like so:
var results = new List<Result>();
foreach (var class1 in class1s) //class1s is a List of Class1
{
foreach (var class2 in class1.Class2s)
{
results.Add(new Result()
{
Class1Id = class1.Id,
Name = class2.Name,
Value = class2.Value,
};
}
}
How can I do this via a linq query?
I have tried the following:
IList<Result> list = class1s.Select(c => c.Class2s.Select(c2 => new Result()
{
Class1Id = c.Id,
Type = c2.Type,
Name = c2.Name,
}).ToList()).ToList();
But this fails with the error:
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<Results>' to 'System.Collections.Generic.IList<Results>'. An explicit conversion exists (are you missing a cast?)
NOTE:
The duplicates do not answer the question as they do not address the issue when the resultant list is a list of the inner classes AND using a property of the inner class.
Retrieving data from a list of parents and children can be done easily in query format by using two from statements
var results = from parent in class1s
from child in parent.Class2s
select new Result {
Class1Id = parent.Id,
Name = child.Name,
Value = child.Value,
};
var list=results.ToList();
In the fluent format, you can use SelectMany
var list = class1s.SelectMany(parent => parent.Class2s,
(parent,child)=>
new Result {
Class1Id = parent.Id,
Name = child.Name,
Value = child.Value
}
).ToList();
I prefer the first form for obvious reasons
Notice that I use the SelectMany overload that accepts a result selector. Without it I'd have to use a Select inside the first selector function, resulting in even more cumbersome code
You can do this in non-query format using the following:
results = class1s.SelectMany(c => c.Class2s.Select(c2 => new Result()
{
Class1Id = c.Id,
Name = c2.Name,
Value = c2.Value,
})).ToList();
Note that it's very similar to your original attempt but using SelectMany on the class1s rather than Select.

How to assign a anonymous type to a model?

How to assign a anonymous type to a model?
Using ViewBag I could easily assign like that:
ViewBag.certType = comboType.ToList();
I am removing all ViewBags from my system and now I am trying like that:
model.storeLocations = comboType.ToList();
I am getting the following error:
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>'
to 'int' S:\Projects\tgpwebged\tgpwebged\Controllers\AdminController.cs
376 40 tgpwebged
Model:
public class TipoDocumentoModel
{
public sistema_DocType Type { get; set; }
public IEnumerable<string> Indices { get; set; }
public IEnumerable<string> NonAssoIndices { get; set; }
public int storeLocations { get; set; }
}
controller:
public ActionResult AdminSettingAddTipo()
{
SettingsModels.TipoDocumentoModel model = new SettingsModels.TipoDocumentoModel();
//Pega os indices e locais de armazenamentos cadastrados no sistema
using (tgpwebgedEntities context = new tgpwebgedEntities())
{
var obj = from u in context.sistema_Indexes select u.idName;
model.Indices = obj.ToList();
var comboType = from c in context.sistema_Armazenamento
select new
{
id = c.id,
local = c.caminhoRepositorio
};
model.storeLocations = comboType.ToList();
}
return PartialView(model);
}
First problem is you are trying to assign a List<> of items to an int property.
Easy way extract out a named class from the anonymous projection.
//model
public List<MyClass> storeLocations { get; set; }
//snip
var comboType = from c in context.sistema_Armazenamento
select new MyClass
{
id = c.id,
local = c.caminhoRepositorio
};
storeLocations = comboType.ToList();
Other Options
If you still want the dynamic behavior you could change your property to be dynamic
Project into a Tuple<int, string>() (guessing on second type)
If the end result is a drop down list you could project into a SelectList()

Categories

Resources