Cast IEnumerable<T> to ObservableCollection<T> without constructor injection the IEnumerable<T> - ienumerable

How can I do that?
thats a no go:
ObservableCollection obsCol = new ObservableCollection(myIEnumerable);
scenario:
var query = from c in customers
select new Customer()
{
Products = from p in products
where p.Id = c.Id
select p
};
Products is a ObservableCollection so it can not take the IEnumerable result from the select above...
How to cast?

Like this:
ObservableCollection obsCol = new ObservableCollection(myIEnumerable.ToList());
Note that the ObservableCollection instance will not reflect changes to the customers list.
EDIT: The Select extension method returns an instance of a compiler-generated iterator class. Since this class does not inherit ObservableCollection, it is impossible to cast it to one.

Related

How to call the declare type methods avoiding dynamic binding?

Person[] p = new Person[5];
p[0] = new Student();
p[1] = new Student();
...
Arrays.sort(p);
Here Person is the parent class and Student is the child class. There is an overridden compareTo() method both in Person class and Student class. I want to sort Person array based on the method in Person class not in Student class. But JAVA's dynamic binding calling the method in Student class as Student is the actual type. How to solve it?

Linq to select top 1 related entity

How can I include a related entity, but only select the top 1?
public EntityFramework.Member Get(string userName)
{
var query = from member in context.Members
.Include(member => member.Renewals)
where member.UserName == userName
select member;
return query.SingleOrDefault();
}
According to MSDN:
"Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities."
http://msdn.microsoft.com/en-us/data/jj574232
There is also a uservoice item for this functionality:
http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method
The approach to use an anonymous object works, even though it's not clean as you wish it would be:
public Member GetMember(string username)
{
var result = (from m in db.Members
where m.Username == username
select new
{
Member = m,
FirstRenewal = m.Renewals.FirstOrDefault()
}).AsEnumerable().Select(r => r.Member).FirstOrDefault();
return result;
}
The FirstRenewal property is used just to make EF6 load the first renewal into the Member object. As a result the Member returned from the GetMember() method contains only the first renewal.
This code generates a single Query to the DB, so maybe it's good enough for You.

What does the "...parameterless constructors and initializers are supported..." error mean?

I'm getting this error:
Only parameterless constructors and initializers are supported in LINQ to Entities.
When trying to run this code (found this code here and made test database to play around with):
XElement xml = new XElement("contacts",
from c in db.Contacts
orderby c.ContactId
select new XElement("contact",
new XAttribute("contactId", c.ContactId),
new XElement("firstName", c.FirstName),
new XElement("lastName", c.LastName))
);
where db is the auto created entities object. Any ideas on how to get this to work?
I believe it's objecting to the fact that you're using an XElement constructor that takes parameters in your "select" clause. Since XElement doesn't have a parameterless constructor, you might need to change your code to select an anonymous type, and initialize the XElement collection after the fact.
var els = from c in db.Contacts
orderby c.ContactID
select new { c.ContactID, c.FirstName, c.LastName };
var xml = new XElement("contacts",
els.ToList()
.Select(e => new XElement("contact",
new XAttribute("contactID", e.ContactID),
new XElement("firstName", e.FirstName),
new XElement("lastName", e.LastName))));
That's untested, but hopefully gives you the idea. I'm doing the EF query first, and then calling ToList() on it so that I can select the XElement collection using Linq to Objects rather than EF.
I would rewrite it like this:
XElement xml2 = new XElement("contacts",
from c in
((IEnumerable<Contact>)(from c in Contacts
orderby c.ContactId
select c))
select new XElement("contact",
new XAttribute("contactId", c.ContactId),
new XElement("firstName", c.FirstName),
new XElement("lastName", c.LastName))
);
The point is to separate LINQ execution tree from XElement instantiation. By casting LINQ query from IQueriable to IEnumerable, you will separate code LINQ will use to get data from code that is going to create your XElements.

Entity Framework using Generic Predicates

I use DTO's to map between my Business and Entity Framework layer via the Repository Pattern.
A Standard call would look like
public IClassDTO Fetch(Guid id)
{
var query = from s in _db.Base.OfType<Class>()
where s.ID == id
select s;
return query.First();
}
Now I wish to pass in filtering criteria from the business layer so I tried
public IEnumerable<IClassDTO> FetchAll(ISpecification<IClassDTO> whereclause)
{
var query = _db.Base.OfType<Class>()
.AsExpandable()
.Where(whereclause.EvalPredicate);
return query.ToList().Cast<IClassDTO>();
}
The Call from the business layer would be something like
Specification<IClassDTO> school =
new Specification<IClassDTO>(s => s.School.ID == _schoolGuid);
IEnumerable<IClassDTO> testclasses = _db.FetchAll(school);
The problem I am having is that the .Where clause on the EF query cannot be inferred from the usage. If I use concrete types in the Expression then it works find but I do not want to expose my business layer to EF directly.
Try making FetchAll into a generic on a class instead, like this:-
public IEnumerable<T> FetchAll<T> (Expression<Func<T,bool>> wherePredicate)
where T:IClassDTO //not actually needed
{
var query = _db.Base.OfType<T>()
.AsExpandable()
.Where(wherePredicate);
return query;
}
pass in school.Evalpredicate instead. FetchAll doesn't appear to need to know about the whole specification, it just needs the predicate, right? If you need to cast it to IClassDTO, do that after you have the results in a List.

How to relate entities that are not directly mapped through a navigation property

I have an object that has been populated with the contents of four different related entities. However i have another entity in which i cannot include as part of the query due to it not being related in the navigation properites directly to the IQueryable table i am pulling. The entity i am trying to include is related to one of the four different entities that have been included successfully.
Is there a way to include(during db hit or afterwards) this entity as part of the overall object i am creating?
Here is an example of what my calls look like to build the CARTITEM object:
public List<CARTITEM> ListCartItem(Guid cartId)
{
//Create the Entity object
List<CARTITEM> itemInfo = null;
using (Entities webStoreContext = new Entities())
{
//Invoke the query
itemInfo = WebStoreDelegates.selectCartItems.Invoke(webStoreContext).ByCartID(cartId).ToList();
}
//Return the result set
return itemInfo;
}
here is the selectCartItems filter(Where i would normally do the includes):
public static Func<Entities, IQueryable<CARTITEM>> selectCartItems =
CompiledQuery.Compile<Entities, IQueryable<CARTITEM>>(
(cart) => from c in cart.CARTITEM.Include("ITEM").Include("SHIPPINGOPTION").Include("RELATEDITEM").Include("PROMOTION")
select c);
from this i have my CARTITEM object. Problem is i want to include the PROMOTIONTYPE table in this object, but since the CARTIEM entity doesn't have a navigation property directly to the PROMOTIONTYPE table i get an error.
Let me know if you need any more clarification.
Thanks,
Billy
You can use join and if it is the same database and server it should generate the join in SQL and do it all in one call...
LinqToEnties join example