Entity Framework one-to-one relationship - Unable to determine the principal - entity-framework

I have 2 models:
public class TransactionHistory : IDbEntity {
[Key]
public int ID { get; set; }
public ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity {
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
public TransactionHistory TransactionHistory { get; set; }
}
There's a one to one relationship between TransactionHistory and ItemHistory, ItemHistory MUST have a TransactionHistory but TransactionHistory may or may not have an ItemHistory.
I want to be able to do this in code:
var test = db.ItemHistory.Include(x => x.TransactionHistory).ToList();
As well as:
var test2 = db.TransactionHistory.Include(x => x.ItemHistory).ToList();
But I only want a single FK on the ItemHistory table.
With the code I've listed I get this error:
Unable to determine the principal end of an association between the types 'InventoryLibrary.DomainModels.TransactionHistory' and 'InventoryLibrary.DomainModels.ItemHistory'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
How is this achieved in Entity Framework code first data annotations?

Firstly, you have to mark foreign keys by virtual keyword to enable overrides.
public class TransactionHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public virtual ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
[Required]
public virtual TransactionHistory TransactionHistory { get; set; }
}
If HistoryItem must have Transaction History, add DataAnnotation [Required], which makes it non-nullable.
Finally, wonder, if you want to have one-to-one relationship. I imagine you'd like to have many transaction history entries. Am I right? If not - let me know.
To create one-to-many relationship, use IEnumerable<> type.

Related

How can I add two property in my model in EF code first from one model?

I want to add two properties from the city model:
after migration this error shows up:
Unable to determine the relationship represented by navigation
'City.Orders' of type 'ICollection'. Either manually configure
the relationship, or ignore this property using the '[NotMapped]'
attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
here is my code :
public class Order
{
public virtual City FromCity { get; set; }
public virtual City ToCity { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
I suppose your model is more complicated than just FromCity and ToCity because I don't think it's a good idea to store such information in a different table. Yet, You can use inheritance in this case.
The table-per-hierarchy (TPH) pattern is used by default to map the inheritance in EF. TPH stores the data for all types in the hierarchy in a single table.
However, for your scenario, you can have a base class that holds all related attributes.
public class CityBase
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
Then suppose you need two entities as per your scenario:
public class FromCity : CityBase
{
public virtual ICollection<Order> Orders { get; set; } = null!;
}
public class ToCity : CityBase
{
public virtual ICollection<Order> Orders { get; set; } = null!;
}
And the order entity:
public class Order
{
public int Id { get; set; }
public string OrderTitle { get; set; } = string.Empty;
public virtual FromCity FromCity { get; set; } = null!;
public virtual ToCity ToCity { get; set; } = null!;
}
This approach can solve your problem with a One-to-Many relationship between Orders and FromCity, ToCity as per below diagram:

because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them

I have implemented following generic model as base model and two models derived from it and i need one to many relationship. I have used fluent api to create the relationships but i get the error mentioned in the title.
Would you please see if you find any thing wrong in my code.
public abstract class ModelBase<T> : BaseEntity, IModelBase<T>
{
public virtual T Id { get; set; }
}
[Table("VehicleModel", Schema = "Tracker")]
public class VehicleModelModel : ModelBase<int>
{
public string Company { get; set; }
public string ModelName { get; set; }
public byte LiPerKM { get; set; }
public virtual ICollection<VehicleModel> Vehicles { get; set; }
[Table("Vehicle", Schema = "Tracker")]
public class VehicleModel : ModelBase<Guid>
{
public string VehicleName { get; set; }
public string LicensePlate { get; set; }
public int VehicleModelId { get; set; }
public virtual VehicleModelModel Model { get; set; }
public virtual TrackerModel Tracker { get; set; }
[Required]
public virtual DriverModel Driver { get; set; }
modelBuilder.Entity<VehicleModel>()
.HasRequired<VehicleModelModel>(s => s.Model)
.WithMany(s => s.Vehicles)
.HasForeignKey(s => s.VehicleModelId);
Here I get this error:
entity types 'VehicleModelModel' and 'VehicleModel' cannot share table 'VehicleModels' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

EF Code first : set optional one to one relationship with data annotation

I've the following situation I try to solve : I've 2 tables, a Course table with some fields and a CourseDescription table which is optional (so Course may have a CourseDescription but CourseDescription must have a Course). I'm trying to set this up. So far, here's what I have :
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public virtual CourseDescription CourseDescription { get; set; }
}
public class CourseDescription
{
[Key, ForeignKey("Course")]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
public int CoursesID { get; set; }
[ForeignKey("CoursesID")]
public Course Course { get; set; }
}
This "works" meaning that EF doesn't complains about my model but the relation is not properly done because EF associate the PK of CourseDescription with the PK of Course. In my database, this is not the case (ex : CourseDescription.ID=1 is associated with CourseDescription.CoursesID=3, not 1).
Is there a way to fix that with data annotation ? I know I can use the fluent API but I don't want to override the model building just for that (unless there's no other way).
Thanks
Well, I think you have two choices:
Configure an one to many relationship
If you want to map the FK of the relationship between Course and CourseDescription, and you don't want to declare that FK property as Key of the CourseDescription entity, then, you don't have other choice that configure an one-to-many relationship. In that case your model would be like this:
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<CourseDescription> CourseDescriptions { get; set;}
}
public class CourseDescription
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
[ForeignKey("Course")]
public int CourseID { get; set; }
public Course Course { get; set; }
}
Configure an one-to-one relationship but not map the FK of the
relationship
The only way that EF lets you map the FK in an one-to-one relationship is when the FK is declared as a PK too, so if you want to have diferent Ids in both entities and you want to stablish an one-to-one relationship, then you could do something like this:
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public CourseDescription CourseDescription { get; set;}
}
public class CourseDescription
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
[Required]
public Course Course { get; set; }
}
And work with the navigations properties.
It looks like you should not use ForeignKey attribute for ID property of CourseDescription class as you don't want to have an association between primary keys. Try to remove it.
Edit: It looks like I misunderstood the question previous time.
You can have your CourseDescription this way.
public class CourseDescription
{
[Key, ForeignKey("Course")]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
public Course Course { get; set; }
}
In this case you don't need to have CoursesID field. Entities will be connected by primary keys.

Entity Framework One to Many Relationship without PK

I have two to be related entities as below :
public class VehicleExtraEntity
{
public int Id { get; set; }
public Guid NameKey { get; set; }
public virtual ICollection<WordEntity> WordsOfName { get; set; }
}
And the other entity :
public class WordEntity
{
public int Id { get; set; }
public string Content { get; set; }
public Guid Key { get; set; }
}
My purpose is write multi language supported db tables. For example ;
WordEntity1 : {Id=1, Content="Child Seat", Key="abcdef-12456"}
WordEntity2 : {Id=2, Content="Çocuk Koltuğu", Key="abcdef-12456"} --> Same Key
VehicleExtraEntity1 : {Id=1, NameKey = "abcdef-123456"}
I have tried fluent api but that support only relationships with navigation property. And it wants to me use many to many relationship. But I want resolve my problem as I wrote as above.

Relationship mapping table with additional properties?

I have three classes:
public partial class Student : Contact
{
//Inherited from Contact:
//public int ContactId { get; set; }
//public string FirstName { get; set; }
//public string LastName { get; set; }
public virtual StudentExam StudentExam { get; set; }
}
public partial class Exam
{
public int ExamId { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public virtual StudentExam StudentExam { get; set; }
}
public partial class StudentExam
{
public byte Score { get; set; }
public int ContactId { get; set; }
public int ExamId { get; set; }
public virtual Student Student { get; set; }
public virtual Exam Exam { get; set; }
}
When trying to initialize the DbContext, it throws a ModelValidationException:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'StudentExam' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'StudentExams' is based on type 'StudentExam' that has no keys defined.
I tried changing the StudentExam class' properties to the following:
[Key, ForeignKey("Student"), Column(Order = 0)]
public int ContactId { get; set; }
[Key, ForeignKey("Exam"), Column(Order = 1)]
public int ExamId { get; set; }
Now I get this exception:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'StudentExam_Student_Source' in relationship 'StudentExam_Student'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'StudentExam_Exam_Source' in relationship 'StudentExam_Exam'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Is there any way to achieve this in with data annotations (I don't like using the fluent API when I can use data annotations; The fluent API leads to messy code.
It is not about data annotations or fluent api but about incorrectly defined classes - relations defined in your classes cannot be mapped at all because they are not valid at relational level. You must modify your classes:
public partial class Student : Contact
{
public virtual ICollection<StudentExam> StudentExams { get; set; }
}
public partial class Exam
{
...
public virtual ICollection<StudentExam> StudentExams { get; set; }
}
Once you have this relations defined you can use your data annotations for defining keys in StudentExam class and it will work.
Btw. fluent api doesn't lead to messy code. Messy code is created by programmer, not by API. Data annotations in turn violates POCO principle.