Retrieving entities with related tables c# using REST API2 - c#

I am building a web API that is suppose to populate data from a linked child table using a where clause.
I have attempted using include() with where() as per eager loading but without success.
public IQueryable<Market> getAllActive()
{
return db.Markets.Where(c => c.IsActive == true).Include(d => d.TravelCentres.Where(e => e.IsActive == true));
}
On researching, there are recommendations that I use explicit loading but it keeps error about the need to cast the data type. I am lost of ideas at the moment and will appreciate any help. Here is my code:
private TravelCentresDbContext db = new TravelCentresDbContext();
public IQueryable<Market> getAllActive()
{
//return db.Markets.Where(c => c.IsActive == true).Include(d => d.TravelCentres);
var result = db.Markets
.Where(c => c.IsActive == true)
.Select(p => new
{
Market = p.MarketId,
TravelCentres = p.TravelCentres.Where(x => x.IsActive == true)
});
return (IQueryable<Market>)result;
}
I get this exception message Unable to cast object of type
'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType42[System.String,System.Collections.Generic.IEnumerable1[TravelCentres.Models.TravelCentre]]]'
to type 'System.Linq.IQueryable1[TravelCentres.Models.Market]'.
Blockquote

result is not an IQuerytable<Market>, it's an IQueryable of an anonymous type with properties Market and TravelCenters. So (IQueryable<Market>)result is an invalid cast. It would be advisable to create a model with Market and TravelCenters properties and then return that.
public class MyModel
{
public int MarketId { get; set; }
public IEnumerable<TravelCentre> TravelCentres { get; set; }
}
.
var result = db.Markets
.Where(c => c.IsActive == true)
.Select(p => new MyModel()
{
Market = p.MarketId,
TravelCentres = p.TravelCentres.Where(x => x.IsActive == true)
});
return (IQueryable<MyModel>)result;

Related

c# - query nested type with LINQ

I have a model that looks like the following:
public class MyType{
public string Id {get;set;}
public string Name{get;set;}
public List<MyType> Children{get;set;}
}
and in my data I have just two level data, meaning my objects will look like:
{
MyType{"1","firstParent",
{
MyType{"2","firstChild",null},
MyType{"3","secondChild",null}}
},
MyType{"4","secondParent",
{
MyType{"5","firstChild",null},
MyType{"6","secondChild",null}}
}
}
How do I query to get MyType object with a specific Id where it might be a parent or child?
The following will return only parents.
collection.FirstOrDefault(c => c.id==id)
You can use Any with a recursive local function to find objects on any level (your data structure would seem to indicate a deeper level is possible)
bool hasIdOrChildren(MyType t, string localId)
{
return t.Id == localId || (t.Children != null && t.Children.Any(o => hasIdOrChildren(o, localId)));
}
collection.FirstOrDefault(c => hasIdOrChildren(c, id));
Or using pre C#7 syntax:
Func<MyType, string, bool> hasIdOrChildren = null;
hasIdOrChildren = (MyType t, string localId) =>
{
return t.Id == localId || (t.Children != null && t.Children.Any(o => hasIdOrChildren(o, localId)));
};
collection.FirstOrDefault(c => hasIdOrChildren(c, id));
If you are only interested in one level, you can drop the reclusiveness:
collection.FirstOrDefault(c => c.Id == id || (c.Children != null && c.Children.Any(o => o.Id == id)));
Edit
The code above gives the parent if any child has the id, you can also flatten the whole tree structure using SelectMany also with a recursive function:
IEnumerable<MyType> flattenTree(MyType t)
{
if(t.Children == null)
{
return new[] { t };
}
return new[] { t }
.Concat(t.Children.SelectMany(flattenTree));
};
collection
.SelectMany(flattenTree)
.FirstOrDefault(c => c.Id == id);
This method can be useful for any type of processing where you need to flatten the tree.
You could build a list of all MyType including children and then query on it like this :
collection.SelectMany(c => c.Children).Concat(collection).Where(c => c.id == id)
I think you're looking for
var flattenedList = IEnumerable.SelectMany(i => i.ItemsInList);
This flattens the list and gives back one list with all items in it.
In your case you need to select
collection.SelectMany(c => c.Type).Concat(collection).Where(item => item.Id == 5);
MSDN
You still got the childs in your joined parents here, but you can still erase them or ignore them.
I think, you should flatten collection using SelectMany method, then use FirstOrDefault to get element by id:
MyType selected = collection
.SelectMany(obj => new MyType[] {obj, obj.NestedList})
.FirstOrDefault(obj => obj.id == id);

How to include only some items of internal list with LINQ to Entities

I have following entities (simplified for readability):
public class Country
{
public List<NameLocalized> Names;
}
public class NameLocalized
{
public string Locale;
public string Value;
}
I also have a DbSet<Country> Countries in my context. How to write a LINQ query which will return the list of countries but with filtered Names (so Names list will contain only single item based on specified locale. Something like this (however, this is not a working example)
public List<Country> GetCountries(string locale)
{
var result = context.Countries.Include(c => c.Names.Select(n => n.Locale == locale)).ToList();
return result;
}
How to achieve this in 2 steps if not possible in one
public List<Country> GetCountries(string locale)
{
//I have to use Include for eager loading
var tempResult = context.Countries.Include(c => c.Names);
var result = //Some code to convert tempResult to result, where only interesting locale is included
return result;
}
I am trying following code to remove unnecessary items, but it does not work too
result.ForEach(c => c.Names.ToList().RemoveAll(n => n.Locale != locale));
UPDATE:
I have managed to remove items with following code (using extension method)
public static void RemoveAll<T>(this ICollection<T> collection,Predicate<T> predicate)
{
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
collection.Where(entity => predicate(entity))
.ToList().ForEach(entity => collection.Remove(entity));
}
result.ForEach(c => c.Names.RemoveAll(n => n.Locale != locale));
UPDATE2:
With the help of answers and comments I was able to succeed. Details are at Convert Entity with navigation property to DTO using IQueryable
Since your model defines Country as something that has multiple Names, it may be confusing to have a Country instance that only has one of its Names. Instead, create a separate type to represent the concept of the information that is known about a Country for a given locale.
public class LocaleCountry
{
public int CountryId {get;set;}
public string Name {get;set;}
public string Locale {get;set;}
}
public List<LocaleCountry> GetCountries(string locale)
{
var result = context.Countries
.Select(c => new LocaleCountry
{
CountryId = c.Id,
Name = c.Names
.Where(n => n.Locale == locale)
.Select(n => n.Name)),
Locale = locale
})
.ToList();
return result;
}
public List<Country> GetCountries(string locale)
{
var result = context.Countries.Select(c => new Country { Names = c.Names.Select(n => n.Locale == locale).ToList() }).ToList();
return result;
}
public List<Country> GetCountries(string locale)
{
var result = context.Countries.Where(c => c.Names.Any(n => n.Locale == locale)).ToList();
result.ForEach(c => c.Names = c.Names.Where(n => n.Locale == locale).ToList());
return result;
}

Best Comparison Algorithm using Entity Framework

I was wondering what was the best approach to compare multiple objects that are created and having the state of the objects changed to Inactive (Deleted), while creating history and dependencies.
This also means im comparing past and present objects inside a relational table (MarketCookies).
Id | CookieID | MarketID
The ugly solution i found was calculating how many objects had i changed.
For this purpose lets call the items of the Past: ListP
And the new items: ListF
I divided this method into three steps:
1 - Count both lists;
2 - Find the objects of ListP that are not present in List F and change their state to Inactive and update them;
3 - Create the new Objects and save them.
But this code is very difficult to maintain.. How can i make an easy code to maintain and keep the functionality?
Market Modal:
public class Market()
{
public ICollection<Cookie> Cookies {get; set;}
}
Cookie Modal:
public class Cookie()
{
public int Id {get;set;}
//Foreign Key
public int CookieID {get;set}
//Foreign Key
public int MarketID {get;set;}
}
Code:
public void UpdateMarket (Market Market, int Id)
{
var ListP = MarketCookiesRepository.GetAll()
.Where(x => x.MarketID == Id && Market.State != "Inactive").ToList();
var ListF = Market.Cookies.ToList();
int ListPCount = ListP.Count();
int ListFCount = ListF.Count();
if(ListPCount > ListFCount)
{
ListP.Foreach(x =>
{
var ItemExists = ListF.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Delete the Object
}
});
ListF.Foreach(x =>
{
var ItemExists = ListP.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Create Object
}
});
}
else if(ListPCount < ListFCount)
{
ListF.Foreach(x =>
{
var ItemExists = ListP.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Create Objects
}
});
ListP.Foreach(x =>
{
var ItemExists = ListF.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Delete Objects
}
});
}
else if(ListPCount == ListFCount)
{
ListP.Foreach(x =>
{
var ItemExists = ListF.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Delete Objects
}
});
ListF.Foreach(x =>
{
var ItemExists = ListP.Where(y => y.Id == x.Id).FirstOrDefault();
if(ItemExists == null)
{
//Create Objects
}
});
}
}
Without a good, minimal, complete code example that clearly illustrates the question, it's hard to know for sure what even a good implementation would look like, never mind "the best". But, based on your description, it seems like the LINQ Except() method would actually serve your needs reasonably well. For example:
public void UpdateMarket (Market Market, int Id)
{
var ListP = MarketCookiesRepository.GetAll()
.Where(x => x.MarketID == Id && Market.State != "Inactive").ToList();
var ListF = Market.Cookies.ToList();
foreach (var item in ListP.Except(ListF))
{
// set to inactive
}
foreach (var item in ListF.Except(ListP))
{
// create new object
}
}
This of course assumes that your objects have overridden Equals() and GetHashCode(). If not, you can provide your own implementation of IEqualityComparer<T> for the above. For example:
// General-purpose equality comparer implementation for convenience.
// Rather than declaring a new class for each time you want an
// IEqualityComparer<T>, just pass this class appropriate delegates
// to define the actual implementation desired.
class GeneralEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _getHashCode;
public GeneralEqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode)
{
_equals = equals;
_getHashCode = getHashCode;
}
public bool Equals(T t1, T t2)
{
return _equals(t1, t2);
}
public int GetHashCode(T t)
{
return _getHashCode(t);
}
}
Used like this:
public void UpdateMarket (Market Market, int Id)
{
var ListP = MarketCookiesRepository.GetAll()
.Where(x => x.MarketID == Id && Market.State != "Inactive").ToList();
var ListF = Market.Cookies.ToList();
IEqualityComparer<Cookie> comparer = new GeneralEqualityComparer<Cookie>(
(t1, t2) => t1.Id == t2.Id, t => t.Id.GetHashCode());
foreach (var item in ListP.Except(ListF, comparer))
{
// set to inactive
}
foreach (var item in ListF.Except(ListP, comparer))
{
// create new object
}
}

Error using Serge Zab's helper for optgroup dropdowns

I'm trying to work with the optgroup dropdown helper from Serge Zab that can be found here.
This is my category table:
As you can see I have a category and a category can also be categoryparent from a category. I want to have the parentcategorys as optgroup and the children as options of the optgroup. (Only the children can be selected)
In my ViewModel:
public short? CategoryId { get; set; }
public IEnumerable<ReUzze.Helpers.GroupedSelectListItem> GroupedTypeOptions { get; set; }
In my Controller:
[Authorize] // USER NEEDS TO BE AUTHORIZED
public ActionResult Create()
{
ViewBag.DropDownList = ReUzze.Helpers.EnumHelper.SelectListFor<Condition>();
var model = new ReUzze.Models.EntityViewModel();
PutTypeDropDownInto(model);
return View(model);
}
[NonAction]
private void PutTypeDropDownInto(ReUzze.Models.EntityViewModel model)
{
model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get()
.OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
.Select(t => new GroupedSelectListItem
{
GroupKey = t.ParentId.ToString(),
GroupName = t.ParentCategory.Name,
Text = t.Name,
Value = t.Id.ToString()
}
);
}
In my View:
#Html.DropDownGroupListFor(m => m.CategoryId, Model.GroupedTypeOptions, "[Select a type]")
When I try to run this I always get the error:
Object reference not set to an instance of an object.
I get this error on this rule : .OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
Can anybody help me find a solution for this problem?
Your error message suggests that either a t is null or a t.ParentCategory is null.
You can fix the error by simply checking for nulls, but this may or may not give you the desired output, depending on whether you also want to include categories that don't have a parent.
model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get()
.Where(t => t.ParentCategory != null)
.OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
.Select(t => new GroupedSelectListItem
{
GroupKey = t.ParentId.ToString(),
GroupName = t.ParentCategory.Name,
Text = t.Name,
Value = t.Id.ToString()
});
I'm assuming your CategoryRepository can't return a null t, but if it can, you'd adapt the where to be:
.Where(t => t != null && t.ParentCategory != null)
The problem is that not all of your entities returned will have a ParentCategory.
It seems you should only be selecting the children and not the parents.
Try this:
model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get()
.Where(t => t.ParentCategory != null)
.OrderBy(t => t.ParentCategory.Name).ThenBy(t => t.Name)
.Select(t => new GroupedSelectListItem
{
GroupKey = t.ParentId.ToString(),
GroupName = t.ParentCategory.Name,
Text = t.Name,
Value = t.Id.ToString()
}
);

Linq OrderedQueryAble Error

First Thing's First I have a class to manipulate some data through a linq variable:
public class Result
{
public bool LongerThan10Seconds { get; set; }
public int Id { get; set; }
public DateTime CompletionTime { get; set; }
}
Then in a Separate class I'm using this to grab info from a linq var
using (var data = new ProjectEntities())
{
Result lastResult = null;
List<Result> dataResults = new List<Result>();
foreach(var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time)))
{
if (lastResult != null)
{
if (subResult.CompletionTime.Subtract(lastResult.CompletionTime).Seconds > 10)
dataResults.Add(subResult);
}
lastResult = subResult;
}
however I get the error:
Linq.IOrderedQueryAble does not contain a definition for 'CompletionTime' and no Extension method 'CompletionTime' accepting a first argument of type 'System.Linq.IOrderedQueryable.
Is anyone able to provide a solution to get around this would be much appreciated been trying to figure it out for a while but seems a bit difficult in terms of a DateTime Variable.
Your problem is that subResult holds an IOrderedQueryable (presumably an IOrderedQueryable<Result>) rather than a Result.
You have this in the foreach: var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time)). Notice what's inside the Select: Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time). That will return an IOrderedQueryable<T>, not a T (where T is whatever type is in the data.Status collection).
You need to either get a single value out of that IOrderedQueryable, using First() or some similar method, like this:
var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time).First())
... or flatten your IEnumerable<IQueryable<T>> to an IEnumerable<T>:
var subResult in data.Status.Select(x => x.ID).Distinct().SelectMany(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time))
Edit: You may also be having an issue where C# is uncertain what type the var subResult is. If they're all Result type objects, try replacing var subResult with Result subResult.
Looks like you have to use SelectMany instead your second Select method call
data.Status.Select(x => x.ID).Distinct()
.SelectMany(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time))

Categories

Resources