Specified type member is not supported in linq to entities - linq

Hi hope someone can help.
I have an EF4 context with 2 POCO based entities that map on to 2 tables in a legacy SQL2005 database. There are no relationships betwen the tables and no associations between the entity definitions in the context.
public class Venue
{
public Venue(){}
public string LocationCode {get;set;}
public string LocationName {get;set;}
}
public class Booking
{
public Booking(){}
public string LocationCode {get;set;}
public int EventReference {get;set;}
public Venue BookingVenue {get;set;}
public Event BookingEvent {get;set;}
}
public class Event
{
public Event(){}
public int EventReference {get;set;}
public DateTime EventStart {get;set;}
/* plus another 60 or so properties */
}
I can do a LINQ select from each individually but whenever I try and join between Event and Booking I get
The specified type member ‘BookingEvent’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
I've tried all the workarounds I can find across the web (there are no enums, calcualted properties, etc) and I'm more than a little frustrated now.
Help ?
Here's the query in question....
List<Booking> bookings = (from b in CalendarDB.Bookings
join e in CalendarDB.Events join b.EventReference on e.EventReference
select b).ToList();

Without the relationships in the model, I don't think EF can figure out what data to use to join on. Even though your Booking class has a BookingEvent property, EF doesn't just 'know' that it needs to join on the Event table based on Booking.EventReference. Because of that, any query which attempts to use those reference properties will fail.

Related

Xamarin Forms, Grouping Realm

I am using Xamarin forms (.NET Standard project), Realm & MVVM Light and I need to group a list of objects based on the Initial of the last name so that I can display a jumplist within a listview.
I am having a problem when trying to group a RealmObject. I have a model like so...
public class Participant : RealmObject
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Email {get; set;}
public string RegistrationCode {get; set;}
//More properties skipped out for brevity
}
Based on this link, I also have a Grouping class like so...
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
In my viewmodel, I am able to fetch the Participants (i.e IQueryable<Participant>) like so....
var participants = RealmInstance.All<Participant>();
I would now like to be able to group this by Initials of the last name for which I do the following:
var groupedParticipants = from participant in participants
group participant by participant.LastName.Substring(0, 1) into pGroup
orderby pGroup.Key
select new Grouping<string, Participant>(pGroup.Key, pGroup);
which throws the below exception:
System.TypeInitializationException: The type initializer for 'Realms.RealmCollectionBase' threw an exception. ---> System.ArgumentException: The property type IGrouping cannot be expressed as a Realm schema type
I have looked around but unable to find working examples of grouping Realm sets. Any help would be greatly appreciated.
Realm does not support Linq's GroupBy (or Select-based projections).
A workaround would be to take a Realm-based sorted query to a standard List and then perform your Linq GroupBy.
Example (using James Montemagno's Monkey project):
var realmSort = r.All<Monkey>().OrderBy(m => m.Name).ToList();
var sorted = from monkey in realmSort
orderby monkey.Name
group monkey by monkey.NameSort into monkeyGroup
select new Grouping<string, Monkey>(monkeyGroup.Key, monkeyGroup);

Spring Data Repository query hook

In Spring Data is it possible to extend a query that is generated by the find* functions of the repo interfaces?
Given following use case:
My legacy database has an inheritance by table. So given following
#Entity public class Person {
private int id;
private String className;
}
#Entity #PrimaryKeyJoinColumn(name="id") public class Musician extends Person {
String instrument;
}
#Entity #PrimaryKeyJoinColumn(name="id") public class Lawyer extends Person {
String discipline;
}
My repository for Musician:
public interface MusicianRepository extends CrudRepository<Musician, int> {
List<Musician> findAll();
}
Now an entry for a new musician in SQL would be:
insert into Person(id, className) values(1, 'Musician');
insert into Musician(id, instrument) values(1, 'piano');
When a Musician got migrated to a lawyer the old system added one row to Lawyer table without removing Musician by:
insert into Lawyer(id, discipline), values(1, 'finance');
update Person set ClassName = 'Lawyer' where ID = 1;
My MusicianRepo would now find the lawyer since the row in Musician still exists.
I would need some kind of post processor where I could extend the query by adding a where clause with "ClassName = 'Musician'" on all find* methods.
Is this possible somehow?
I think that your JPA mapping is just not correct in terms of inheritance.
I think you want to have "Joined, Multiple Table Inheritance"
Citing from here:
Joined inheritance is the most logical inheritance solution because it
mirrors the object model in the data model. In joined inheritance a
table is defined for each class in the inheritance hierarchy to store
only the local attributes of that class. Each table in the hierarchy
must also store the object's id (primary key), which is only defined
in the root class. All classes in the hierarchy must share the same id
attribute. A discriminator column is used to determine which class the
particular row belongs to, each class in the hierarchy defines its own
unique discriminator value.
Some JPA providers support joined inheritance with or without a
discriminator column, some required the discriminator column, and some
do not support the discriminator column. So joined inheritance does
not seem to be fully standardized yet.
The className column in Person would be your descriminator column. It determines the subclass to instantiate.
Your mapping would be something like this:
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="className")
public class Person {
private int id;
private String className;
}
#Entity
#DiscriminatorValue("Musician")
public class Musician extends Person {
String instrument;
}
#Entity
#DiscriminatorValue("Lawyer")
public class Lawyer extends Person {
String discipline;
}
This way if you query for Lawyer entities JPA would automatically add the where clause to just read rows with className=Lawyer
I did not try the mapping - it should just illustrate the way you should be going.

How do I delete a related object with a 1 to 1 relationship in the Entity Framework?

I'm using EF Model First and in my Employee class I have a Manager property with a 1 to 1 relationship to itself, the Employee class:
public partial class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Employee Manager { get; set; }
}
Now, when I get an existing object from the database and change the manager with:
employee.Manager = otherEmployeeInstance;
Context.Entry(employee).State = System.Data.EntityState.Modified;
Context.SaveChanges();
It works just fine; however, if I want to remove the manager this will not work:
employee.Manager = null;
It looks to me that I first need to "load" the manager (Employee) instance into the context since this makes it work:
var dummyVar = employee.Manager.Id;
employee.Manager = null;
So the question is, what's the best (proper) way to remove a related object?
obviously, when you want to delete an entity of the one-to-one relationship, the EF doesn't allow to delete it without preparing it before. that is, removing any dependent entity information from that entity. Remember, we are using Relational Database system and any breaking relation without any coordination causes to anomaly and failure.
When you want to remove a relation, you can use this at your controller:
employee.Remove(Manager);//Automatically Removes Navigational Properties at both entities
db.SaveChanges();
Instead of this :
employee.Manager = null;

Entity Framework 4 and MVC 3 - Inheritence and Loading Derived Entities

I've got some common properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn) for nearly all of my entities. I decided to have a BaseEntity with these properties and then have all of my other entities inherit from this one.
For example:
BaseEntity --> Question
BaseEntity --> Answer
Now how do I load questions from my model container?
There is no db.Questions or db.Answers any more. Just db.BaseEntities.
Specifically I want to load all questions by their subject - so normally I would say db.Questions.Where(q => q.Subject.Id.Equals(subjectId)).
How do I do this now?
Many thanks,
Pete
First, there are multiple types of inheritance mapping strategies that you can use to configure your database
Table per hierarchy (TPH) - this is used by default, so currently you get only one table in database
Table per type (TPT)
Table per concrete type (TPC)
You can also add sets of concrete types to your DbContext
public class MyDbContext : DbContext
{
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
}
And the most important - I would prefere composition over inheritance in your place. This feels more natural
public class HistoryRecord
{
public User CreatedBy { get; set; }
public User UpdatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
}
and use it as complex type inside Question, Answer, etc
public class Question
{
public HistoryRecord HistoryRecord { get; set; }
}
Do not use a base class for this.
You'll end up with one entity set and have to use typeof(X).
Worst of all, this may break future inheritance of other entities, especially if some are table per type, some are table per hierarchy and some are mixtures of the two.
Instead, use partial classes to define a common interface with the aspect properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn).
Edit: The base entity will also require a table with the PKs of all your entities in it.
This will cause the table to be unnecessarily large and may result in performance hits during queries and inserts.

Populate DTO from several queries

I have a DTO with 40+ properties. But in order to populate all properties I need to execute 4 separate queries. My first query is in charged of getting basic information. For each row returned I run 3 more queries based on the id's given from the main query (N+1 problem). I can set use eager loading but then I'm loading thousands of objects that I don't need.
Should I split my DTO and create a separate DTO for each query I run then link then tie them all together into a central DTO by id?
I was envisioning a final DTO like this.
public class FooDto
{
public string Foo { get; set; }
public string Bar { get; set; }
public FirstDto FirstQueryResults { get; set; }
public SecondDto SecondQueryResults { get; set; }
public ThirdDto ThirdQueryResults { get; set; }
}
Is there a better way of solving this? I'm using Oracle and NHibernate doesn't support multi criterias. Note that I am joining most of my data. The problem comes when I need to query data with a complete new set of criteria.
How about creating a VIEW that joins the data to give the 40 properties all in one go, and basing your DTO on that - whatever a DTO may be ;-)

Resources