EF6 Foreign Key Issue - entity-framework

Here are my models
public class Driver
{
public int Id { get; set; }
public String Name { get; set; }
public int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public String Name { get; set; }
public virtual Driver Driver { get; set; }
public int VehicleGroupId { get; set; }
public virtual VehicleGroup Vehicles { get; set; }
}
I'm getting the following error on updating database:
Unable to determine the principal end of an association between the types 'AppName.Models.Vehicle' and 'AppName.Models.Driver'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I wish to solve the issue using data annotations. I've tried putting foreign key attribute over Driver Navigation property in vehicle model. But no success. Any help is much appreciated.

To solve your problem you need to explicitly set the end of the association like this :
public class Vehicle
{
[Key, ForeignKey("Driver")]
public int Id { get; set; }
public String Name { get; set; }
public virtual Driver Driver { get; set; }
public int VehicleGroupId { get; set; }
public virtual VehicleGroup Vehicles { get; set; }
}
I think your model is inccorect because a driver can use many vehicles in real life ;)

Related

Problem generating foreign key in EF Code First - Unable to determine the principal end of an association

I am trying to enable migrations on a new db that includes the following table relationship:
where HolderID can be NULL. Running enable-migrations gives the error message of "Unable to determine the principal end of an association"
My 2 classes are as follows:
public class Competitor
{
[Key]
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
public virtual Championship Championship { get; set; }
}
public class Championship
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int? HolderID { get; set; }
[ForeignKey("HolderID")]
public virtual Competitor Holder { get; set; }
}
I don't understand how I need to correct my model to reflect the desired database schema structure. I would prefer to use Annotations over fluent api, if possible.
Thanks in advance.
public virtual Championship Championship { get; set; }
needed to be
public virtual ICollection<Championship> Championships { get; set; }

Can't set the Relation between 2 DB Models

I Got This Issue:
I Have the Application User Class Like This
public class ApplicationUser : IdentityUser
{
public ROLES Role { get; set; }
public int? CompanyId { get; set; }
public int? AreaId { get; set; }
public string Document { get; set; }
public bool Enable { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
[ForeignKey("AreaId")]
public virtual Area Area { get; set; }
public virtual ICollection Measures { get; set; }
}
And I Got this another Model:
public class Area
{
public int AreaId { get; set; }
public string AreaName { get; set; }
public int CompanyId { get; set; }
public string UserId { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
[Key, ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }
}
And when i try to:
add-migration
the PM Console throws:
Unable to determine the principal end of an association between the types 'x.Models.ApplicationUser' and 'x.Models.Area'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I have been trying all day but I can't find a way to tell the Entity Framework to recognize the relation.
Any ideas?
Thanks for reading
Add Attribute for AreaId in Area class
[Key]
public int AreaId { get; set; }
and if you want 1-1 relationship for ApplicationUser and Area update your code like
[Unique]
[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
This Post give me the Answer I Need!!!
It's pretty hard to find...
So I let you the post here...
Thanks for all of your help!

Using Entity Framework Data Annotations to Achieve One to Many Relationship With Eager Loading

I've seen plenty of examples not using Data Annotations and can get a one-to-one relationship working, but having difficulty with a one-to-many.
We have parts that we will randomly take sample weights on to make sure our machine house is producing to spec. The one-to-one relationship for Material will load. Having trouble with the QualityMeasurements one-to-many.
Anyone have experience with this?
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Part {
[Key]
public string PartID { get; set; }
public string PartNumber { get; set; }
[ForeignKey("MaterialID")]
public virtual Material Material { get; set; }
public int MaterialID { get; set; }
[ForeignKey("PartNumber")]
public virtual ICollection<QualityMeasurement> Qualities { get; set; }
}
public class Material {
[Key]
public int MaterialID { get; set; }
public string Title { get; set; }
public double Density { get; set; }
}
public class QualityMeasurement {
public int QualityID { get; set; }
[Key]
public string PartNumber { get; set; }
public double UnitWeight { get; set; }
}
You are having troubles because in the one-to-many relationship, the foreign key should be defined at the many side and should relate to the primary key of the one side.
Your model should be something like this:
public class Part {
[Key]
public string PartID { get; set; }
public string PartNumber { get; set; }
[ForeignKey("MaterialID")]
public virtual Material Material { get; set; }
public int MaterialID { get; set; }
public virtual ICollection<QualityMeasurement> Qualities { get; set; }
}
public class QualityMeasurement {
[Key]
public int QualityID { get; set; }
[ForeignKey("PartID")]
public virtual Part Part { get; set; }
public string PartID { get; set; }
public double UnitWeight { get; set; }
}

breeze.js one to many

I'm currently building an SPA with Web API and knockout etc. So far i worte my own simple datacontext and it worked pretty well.
The I bumped in to breeze and thought it might be worth a try. especially I hoped to get a simpler approach on navigation between the entities...
to load a entities or a single entity with breeze worked fine. Working with navigation properties seems not to work. The navigation property is always empty, even though it's a one to many relationship.
Here is my model (simplified):
public class WorkdayHours
{
public int Id { get; set; }
public bool IsWorkDay { get; set; }
...
public Byte WeekDay { get; set; }
}
public class Service
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
public class Shop
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
Then I fetch the entity service ind my SPA as follow:
var query = EntityQuery
.from('Services')
.where('id', 'eq', serviceId)
.expand('BookableDays');
As when teh query is executed I get as result the requested service entity with all the data except the bookableDay property is always an empty array.
When I check the Json answer I see that also the workdayHours are transmitted and breeze even calls my defined ctors for this entities. However they are not linked to the bookableDays property itself.
When checking the genrated DB model, EF generated foreignkeys for service, employee and shop in workdayHours as expected.
Is breeze not capable with having several optional foreignkeys?
Suggestion and ideas highly apprechiated.
Breeze is dependent on Foreign Keys. I had a similar problem. This should solve it:
EF was generating the ForeignKeys for me too and the related Entites where still empty. As far as i know breeze needs the explicit Annotation/Configuration of ForeignKey Fields.
public class Mvl
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MvlId{ get; set; }
public DateTime CreatedAt { get; set; }
[InverseProperty("Mvl")]
public ICollection<MvlOP> MvlOps { get; set; }
public DateTime? ReleasedAt { get; set; }
public DateTime? LockedAt { get; set; }
public DateTime? ClosedAt { get; set; }
//[ConcurrencyCheck]
//public int? RowVersion { get; set; }
[Timestamp]
public byte[] TimeStamp { get; set; }
}
public class MvlOP
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MvlOpId { get; set; }
public long MvlId { get; set; }
[ForeignKey("MvlId")]
public Mvl Mvl { get; set; }
...
}

Schema specified is not valid. Errors: The relationship not loaded because the type is not available

I have the entities Dependency, Product and Access. Dependency is connected to Product and Access. When i try to create a object set of Access with:
this.context.CreateObjectSet<Access>();
It's working... but when i try to create a object set of Product i get this error: Schema specified is not valid. Errors: The relationship 'Model.FK_Product_Dependency' was not loaded because the type 'Model.Dependency' is not available.
Any ideas?
OBS: i'm working with Database to Model, and with EF 4.0
POCO Entities:
public class Dependency
{
public virtual int Id { get; set; }
public virtual int IdParent { get; set; }
public virtual string Name { get; set; }
public virtual decimal Type { get; set; }
public virtual Dependency Parent { get; set; }
}
public class Product
{
public virtual int Id { get; set; }
public virtual int IdDependency { get; set; }
public virtual decimal Type { get; set; }
public virtual string Name { get; set; }
public virtual string Obs { get; set; }
public virtual Dependency Dependency { get; set; }
}
public class Access
{
public virtual int Id { get; set; }
public virtual int IdProfile { get; set; }
public virtual string Name { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<Dependency> Dependencies { get; set; }
}
Solved. So, the POCO entities cannot be in different namespaces/dlls if access each other. In the exemple above, Dependency and Access was in a namespace/dll and Product in another. I thought that was only necessary the POCO entity be the same (properties and name) like the entity mapped by EF, but is necessary that the entities are in the same namespace/dll (only to the entities that access each other).