Help with EF Code First, many to many relationship - entity-framework

Person and EHR(electronic health record) are one to one related.
Person has EHRId nullable and EHR has PersonId not nullable.
At the same time EHR and Person must be many to many related.
Because a person can have many medics (represented by person entity) and a medic can have many EHRs.
I would like to have extra attributes on the join table.
I dont know how to define this in EF.
Please help.
Here are my classes.
public class Person
{
public int ID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public ICollection<UserSpecialist> patients { get; set; }
public int ehrID { get; set; }
public virtual EHR ehr { get; set; }
}
public class EHR
{
public int ID { get; set; }
public bool asthmatic{ get; set; }
public ICollection<UserSpecialist> specialists { get; set; }
public int PersonID { get; set; }
public virtual Person Person { get; set; }
}
public class UserSpecialist
{
public int ID { get; set; }
public DateTime creationDate { get; set; }
public int PersonID { get; set; }
public int EHRID { get; set; }
public virtual Person Person { get; set; }
public virtual EHR EHR { get; set; }
}
When EF tries to create the database throws this error
Unable to determine the principal end
of an association between the types
'Project.Person' and 'Project.EHR'.
The principal end of this association
must be explicitly configured using
either the relationship fluent API or
data annotations.
Please help

Person and EHR are not one-to-one related and they cannot be in EF. What you have defined is bidirectional one-to-many. You have also declared both relations as required because FK's are not nullable.
Real one-to-one can be defined in EF only if EHR's PK (Id) is also FK to Person. Once you define this the part with many-to-many becomes really strange because Person will be related with EHRs of other persons. You domain description is most probably not correct.

Related

one to one relationship with ef core 5 (use 2 FK)

I have these 2 Entities. each book can have one or zero BookDetail (1 to 1 Relationship)
public class Book
{
public int BookId{ get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ISBN { get; set; }
public string Price { get; set; }
public int BookDetailId { get; set; } /* FK for BookDetail */
public BookDetail BookDetail{ get; set; }
}
public class BookDetail
{
public int BookDetailId{ get; set; }
public string Weight { get; set; }
public string NumberOfPages { get; set; }
public DateTime PublicationDate { get; set; }
public int BooklId { get; set; } /* FK for Book */
public Book Book{ get; set; }
}
I want to have 2 sides foreign key, I just find solutions for just one side foreign key but I want to store FK Id of BookDetail on Book and vice versa in EF Core 5.
I know how to configure this relationship with one side FK.
To Model the Fact that a Book can have 0 or 1 BookDetail you have to make the FK on Book, pointing to BookDetail, nullable, check this:
Fluent API Key Relation
and this
public class Book
{
public int BookId{ get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ISBN { get; set; }
public string Price { get; set; }
public int? BookDetailId { get; set; } /* nullable FK to BookDetail */
public BookDetail BookDetail{ get; set; }
}
Is it coherent with reality that a BookDetail cannot exist without the book itself, so in this case the FK from BookDetail to Book must not be nullable.
I would not "warp" the name of the FK so I can leverage EFCore conventions:
public class BookDetail
{
public int BookDetailId{ get; set; }
public string Weight { get; set; }
public string NumberOfPages { get; set; }
public DateTime PublicationDate { get; set; }
public int BookId { get; set; } /* FK to Book by conventions*/
public Book Book{ get; set; }
}
This would be enough for EFCore conventions to figure out that you have a one to one relation and that Book is the Independent memeber of the relation and BookDetail is the dependent one: The Independent is always required.
A little extra info: you might want to check owned entites, your BookDetail entity can be seen as a "complex property" of Book, this would mean though that BookDetail could not have an Id by itself.
Owned Entity Types

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!

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.

EF Code First Entity Mapping with Foreign Key in Mapped Entity

(source: mcainsh.info)
The tables are just for an example, what I am trying to do is map a virtual Manufacturer in the Book entity. I've tried using data annotation similar to below:
[ForeignKey("PublisherId")]
public virtual Publisher { get; set; }
[ForeignKey("Publisher.ManufacturerCompanyId")]
[InverseProperty("ManufacturerId")]
public virtual Manufacturer { get; set; }
Is this something that can be done?
You're configuring incorrectly the foreign keys. To do what you want, your model should be like this:
public class Book
{
public int Id { get; set; }
public string Title{ get; set; }
public int PublisherId { get; set; }
[ForeignKey("PublisherId")]
public virtual Publisher Publisher{ get; set; }
public int ManufacturerId { get; set; }
[ForeignKey("ManufacturerId")]
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Publisher
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
In this model you have two one-to-many relationships, the first between Book and Publisher and the second one between Book and Manufacturer. As you can see in the Book class, if you want to use a FK property you must declare a property of the same type of the PK of the related entity (see PublisherId and ManufacturerId).Now, you can apply the ForeignKey annotation to the navigation property and tell it which property is the foreign key for the relationship, as I show above. Alternatively, you can addForeignKey attribute to the ManufacturerId, along with information telling it which navigation property represents the relationship it is a foreign key for:
[ForeignKey("Manufacturer")]
public int ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
If you want, you don't need to create the FKs properties, EF will do the job for you begin the escene. It will create a FK row in your Books table for each relationship (check the DB after execute your code):
public class Book
{
public int Id { get; set; }
public string Title{ get; set; }
//public int PublisherId { get; set; }
//[ForeignKey("PublisherId")]
public virtual Publisher Publisher{ get; set; }
//public int ManufacturerId { get; set; }
//[ForeignKey("ManufacturerId")]
public virtual Manufacturer Manufacturer { get; set; }
}

How to add entity with one to one association in Entity Framework Code first approach?

I am using EF 4.4 + Code First.
I was trying to add a ChartofAccount entity to DBContext with the Company's key filled, but it ask me to fill the Company's CompanyName as well at validation. I thought DBContext will look up the associate Company for me, instead of trying to add a new Company?
public class ChartofAccount: MasterData
{
public ChartofAccount()
{
Company = new Company();
Category1 = new AccountCatagory();
Category2 = new AccountCatagory();
}
[Key]
[Required]
public string Code { get; set; }
public virtual Company Company { get; set; }
[Required]
public string AccountName { get; set; }
[Required]
[StringLength(3)]
public string AccountCurrency { get; set; }
public virtual AccountCatagory Category1 { get; set; }
public virtual AccountCatagory Category2 { get; set; }
public string Reference { get; set; }
public bool HasTransaction { get; set; }
}
public class Company : MasterData
{
[Key]
public int Id { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
DateTime CurrentAccountPeriod { get; set; }
[Required]
[StringLength(3)]
public string BaseCurrencyCode { get; set; }
}
Sadly, just the primary key of a related entity isn't enough. You need to round trip to the database to obtain the entity in the same data context.
Example:
var Company = db.Company.Single(d => d.ID == id);
ChartofAccountToAdd.Company = Company;
db.ChartofAccount.Add(ChartofAccountToAdd);
db.SubmitChanges();
That will create the relationship with an already existing company.
EDIT:
I completely forgot about this when I answered. Edit your ChartOfAccount model to contain the foreign key for the Company like:
public class ChartofAccount: MasterData
{
{rest of your model}
public int CompanyID { get; set; }
}
and then set the foreign key to that new int property. Entity Framework will create the relationship without any issues. Don't set anything to the Company property on the model.