Entity Framework 4.2 One to many relationship - linq

I have 2 tables in an existing database:
Table1
[Key] public int Id {get; set;}
public int CustomerID {get; set;}
List<Table2> Table2Items {get; set;}
....
Table2
[Key] public int Id {get; set;}
public int customerid {get; set;}
Table1 Table1Item {get; set;}
...
I want to create a one-to-many relationship, such that each record in table1 can have many associated records in table2.
Its normally straight forward using the primary key field in table1 which matches the foreign key field (customerid) in table 2.
But I want to relate the 2 tables based on the CustomerID in table1 with the customerid in table2.
The following appears to relate the 2 tables by using the customerid field in table2 with the primary key in table1, which is not what I require.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Table1>()
.HasMany<Table2>(s => s.Table2Items)
.WithRequired(s => s.Table1Item)
.HasForeignKey(s => s.customerid);
}
How can I modify the code shown above to fit my requirements.

What you are trying to achieve is impossible with current version of Entity Framework. Quoting from https://stackoverflow.com/a/7022799/337294:
It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.
And since Entity Framework does not support unique indexes yet (despite strong demand in their Feature Suggestion page), it has to be the Id property of your Table1 class.

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);

Hibernate Mapping Annotation without Foreign Key

I have 2 tables ( Member, Department)
Member with MemberID, MemberName, DepartmentID
Department with DepartmentID, DepartmentID
Member is one to one to Department,
Department is one to many Member
Is there any ways to map them while creating the model class without using foreign key constraint in database?

Linq-to-Sqlite : Unable to map a TEXT type sqlite column against a System.Double type of model property?

I have a Sqlite database table named Movie whose columns basically store data simply in TEXT or INTEGER type (of course, Sqlite basically stores everything as just string the columns only have an affinity towards the type, if i am not wrong).
I am using Linq-to-Sqlite ORM to query my table data against a model named Movie. Below is the DDL for the table and code for the class.
CREATE TABLE Movie
(
Id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
Title Text,
Rating TEXT,
IsSubtitle INTEGER
)
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public double Rating { get; set; }
public bool IsSubtitle { get; set; }
}
Now when I try to fetch the movie records from the database using the ORM, it throws an exception :
System.InvalidOperationException was caught
HResult=-2146233079
Message=The 'Rating' property on 'Movie' could not be set to a 'System.String' value. You must set this property to a non-null value of type 'System.Double'.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at LinqToSqliteDemoApp.Program.Main(String[] args) in e:\Projects\TestApplications\LinqToSqliteDemoApp\LinqToSqliteDemoApp\Program.cs:line 25
InnerException:
Obviously, it cannot cast the TEXT type of data from the Rating column into the double data type of Movie class.
So I would like to know, is there any workaround to tell the ORM to implicitly map or convert the Rating column data to double data type while retrieving from the database ?
You need to read the docs on sqlite data types http://www.sqlite.org/datatype3.html, so use double in your create table statement

How to persist a model when doing Create / Edit in MVC3 before saving it to the database?

basically I am talking about the thing what we had in ASP.NET, called ViewState.
Here is the example, to keep it simple, I have a model Employee:
public class Employee
{
public string EmployeeId { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
My company created records for employees with their EmployeeId, Name and Company.
The employee needs to enter (update) only his Phone number and Address.
When I present a form in Edit / or Create mode for employee to enter this information, EmployeeID, Name and Company outputted just as text, while Phone and Address are editable fields (Html.EditorFor), which allows to keep values entered in the Model object.
When this form is HTTP posted back, lets say, validation fails, and the form is presented to the user again to correct his input (View(model)).
However the values for EmployeeID, Name and Company are lost, since they were not defined as Html.EditorFor, like Phone and Address, and therefore are not preserved, when the submitted model is being passed again into the View.
How do I preserve (persist) in the Model those properties (that are not editable)?
Thank you.
Simply use Html.HiddenFor and store the values on the page. You could also use the mvc futures project and Html.Serialize it, but then you are mimicking viewstate when it's not necessary.

Specified type member is not supported in linq to entities

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.

Resources