I am new to Entity Framework so I don't know much about it. Currently I am working on My College Project, in that Project I came across a problem where I have two foreign keys refers to the Same column in another table. how can I handle this situation.
Is it necessary to create Navigation Property for Every Foreign key. And if I create another Navigaton property for ContactId then it is necessary to create another Navigation Property in User class like:
public virtual ICollection<BlockedUser> SomePropertyName { get; set; }
please tell me the best way to overcome this problem. I am using Entity Framework 6.
Here are My Model Classes:
public class BlockedUser
{
// User Foreign Key
public int UserId { get; set; } // Composite Primary Key
// User Foreign key
public int ContactId { get; set; } // Composite Primary Key
// User Navigation Property
public virtual User User { get; set; }
}
public class User
{
public int UserId { get; set; } // Primary key
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
// BlockedUser Navigation Property
public virtual ICollection<BlockedUser> BlockedUsers { get; set; }
}
Is it necessary to create Navigation Property for Every Foreign key?
Yes, or more precisely: You need at least one navigation property for every relationship. "At least one" means that you can decide which of the two entities you want to add the navigation property to. It normally depends on the most common use cases in your application if you often want to navigate from entity A to entity B or the other way around. If you want, you can add the navigation properties to both entities but you don't need to.
In your model you apparently have two (one-to-many) relationships. If you want to expose navigation properties in both entities you would need four navigation property and - important! - you have to define which navigation properties form a pair for a relationship (see the [InverseProperty] attribute in the following code snippet).
With data annotations it would like this:
public class BlockedUser
{
[Key, ForeignKey("User"), Column(Order = 1)]
public int UserId { get; set; }
[Key, ForeignKey("Contact"), Column(Order = 2)]
public int ContactId { get; set; }
[InverseProperty("BlockedUsers")]
public virtual User User { get; set; }
[InverseProperty("BlockedContacts")]
public virtual User Contact { get; set; }
}
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public virtual ICollection<BlockedUser> BlockedUsers { get; set; }
public virtual ICollection<BlockedUser> BlockedContacts { get; set; }
}
If you don't want the BlockedContacts collection you can probably just remove it and the [InverseProperty("BlockedContacts")] attribute from the Contact navigation property as well.
You could use attribute ForeignKey to solve your problem. ForeignKey is used to pair navigation property and foreign key property.There is no difference between FK data annotation with Foreign Key property and FK with Navigation Properties. However, the following code will create two foreign keys with different name.
public class BlockedUser
{
// User Foreign Key
[ForeignKey("UserId")]
public int UserId { get; set; } // Composite Primary Key
// User Foreign key
[ForeignKey("BlockedUser_User")]
public int ContactId { get; set; } // Composite Primary Key
// User Navigation Property
public virtual User User { get; set; }
}
public class User
{
public int UserId { get; set; } // Primary key
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
// BlockedUser Navigation Property
public virtual ICollection<BlockedUser> BlockedUsers { get; set; }
}
Related
So I try to create some ASP.NET project with EF Core.
I want to set propert of one entity as primary key and foreign key to another entity. The relationship is 0..1 - 1. I use DataAnnotations:
public class OfficeAssignment
{
[Key, ForeignKey("InstructorID")]
public int InstructorID { get; set; }
public Instructor Instructor { get; set; }
public string Location { get; set; }
}
But I keep getting column InstructorID as PK and InstructorID1 as FK... Any ideas, why EF behaves like that and how can I achieve my goal?
You should follow convention over configuration as much as you can. An OfficeAssignment entity should have an OfficeAssignmentId PK, like this:
public class OfficeAssignment
{
public int OfficeAssignmentId { get; set; }
//Notice that Id does not have an uppercase D
public int InstructorId { get; set; }
public string Location { get; set; }
public Instructor Instructor { get; set; }
}
However, if you don't want to follow normal conventions, the name of the property that goes in the ForeignKey attribute is the opposite of where it's declared:
public class OfficeAssignment
{
[Key, ForeignKey("Instructor")]
public int InstructorId { get; set; }
public string Location { get; set; }
public Instructor Instructor { get; set; }
}
And, if you want to keep it compile-time safe:
public class OfficeAssignment
{
[Key, ForeignKey(nameof(Instructor))]
public int InstructorId { get; set; }
public string Location { get; set; }
public Instructor Instructor { get; set; }
}
It's enough to set primary key attribute([Key]) in the OfficeAssignment class and in Instructor class we need to set such attribute:
[InverseProperty("Instructor")]
on collection of CourseAssignments. That will work as desired.
I have a MasterUserApprovalOfficial entity with two foreign keys, MasterUserId and SoftwareSystemId. EF 7 is smart enough to figure out that these two properties are foreign keys.Here is my MasterUserApprovalOfficial class
public class MasterUserApprovalOfficial
{
public int MasterUserApprovalOfficialId { get; set; }
public int MasterUserId { get; set; }
public MasterUser MasterUser { get; set; }
public int SofwareSystemId { get; set; }
public SoftwareSystem SoftwareSystem { get; set; }
public bool Active { get; set; }
public DateTime CreateDate { get; set; }
public MasterUserApprovalOfficial()
{
CreateDate = DateTime.Now;
}
}
If I look at the table that was created the MasterUserId column was created and named as expected, the SoftwareSystemId column however is created as SoftwareSystemSoftwareSystemId (The name of the class appended to the name of the primary key)
Is there any reason for this?
public int SofwareSystemId { get; set; }
read that property again. there's a t missing :)
the second answer is also right, you don't need properties for the foreign key. A member of the class is enough
Use the ForeignKey and Column attributes to fix this:
[ForeignKey("SoftwareSystem"),Column("SoftwareSystemId")]
public int SoftwareSystemId { get; set; }
By default the foreign key will be added with "Id" behind it, but because you already have a property with that name (and EF doesn't recognize it's the foreignkey apparantly) it gets changed into SoftwareSystemSoftwareSystemId.
I have two model classes one is ApplicationUser and the second is Appointment. Application user includes all users that use the application, in my case, Doctors and Data entry operators. Doctors will be assigned to each appointment and Data entry operators will be making this log to DB. I want to map both these users with appointment. I have tried something like this
public class Appointment
{
public int AppointmentID { get; set; }
public DateTime Date { get; set; }
public int DoctorID { get; set; }
[ForeignKey("DoctorID")]
public virtual ApplicationUser Doctor { get; set; }
public int SystemUserID { get; set; }
public virtual ApplicationUser SystemUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string Mobile { get; set; }
public string FirstNsme { get; set; }
public string LastName { get; set; }
}
But this throws an error
Appointment_Doctor_Target_Appointment_Doctor_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'DoctorID' on entity 'Appointment' does not match the type of property 'Id' on entity 'ApplicationUser' in the referential constraint 'Appointment_Doctor'.
Can anyone point out why this error is occurring and what is the correct approach to this problem?
IdentityUser as all entities in asp.net identity entity framework have string as key. You are trying to map to an int. So either use Guids as foreign keys in your Appointment entity
public class Appointment
{
[Key]
public int AppointmentID { get; set; }
public DateTime Date { get; set; }
public string DoctorID { get; set; }
[ForeignKey("DoctorID")]
public virtual ApplicationUser Doctor { get; set; }
public string SystemUserID { get; set; }
[ForeignKey("SystemUserID ")]
public virtual ApplicationUser SystemUser { get; set; }
}
or change the type of Ids in identity classes to int. You can find help here.
There are multiple issue in your classes.
What is DoctorID? Where it is defined?
You need to first focus on establishing correct relationship between your entities logically.
I think your Appointment class need not contain SystemUserID who added an appointment.
Second if you wanted to share some properties between two user types than create a common class and derive in Doctor and SystemUser.
Add DoctorId into Doctor table along with specific details pertaining to Doctor e.g. Specialty.
SystemUser adds a appointment so the table should contain data related to that i.e. doctorId and appointmentId.
Update:
Based on your comment, you could do something like this. Note its for reference only, you are better person to define a better DB Schema.
public class Appointment
{
public int AppointmentID { get; set; }
public DateTime Date { get; set; }
public int DoctorID { get; set; }
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser Doctor { get; set; }
public int SystemUserID { get; set; }
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser SystemUser { get; set; }
}
public class ApplicationUser
{
public int ApplicationUserId { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string FirstNsme { get; set; }
public string LastName { get; set; }
public UserType UserType { get; set; }
}
public enum UserType
{
Doctor,
SystemUser
}
FURTHER AND MORE COMPLEX ERROR:
I had this error multiple times across 4 linked tables.
Each table had composite keys of 3 - 7 fields,
and one table referenced its own 3-field key with a different mix of its own columns.
I struggled for ages with fixing one sequence of fields (which does fix the error as mentioned in other posts) only to have knock-on effect in other entities.
The solution:
Align all linked tables' FK fields in order of reducing occurrence
ORIGINALLY:
AFTER KEY FIELDS WERE ALIGNED:
And re-ordered all anonymous FK objects in FluentAPI in the DbContext to match the new order.
This fixed all headaches.
I've got the following domain models (pseudo):
public class Camera {
public int Id { get; set; }
}
public class Display {
public int Id { get; set; }
}
public class SetupGroup {
public int Id { get; set; }
public virtual ICollection<CameraDisplayMap> Mappings { get; set; }
}
public class CameraDisplayMap {
public int Id { get; set; }
public Camera Camera { get; set; }
public Display Display { get; set; }
}
which should get mapped the following way:
[Cameras]
Id (primary key)
[Displays]
Id (primary key)
[SetupGroup]
Id (primary key)
[CameraDisplayMap]
Id (foreign key to [SetupGroup]
Camera (foreign key to [Cameras])
Display (foreign key to [Display])
I am aware the data model is not ideal, but it's a requirement in order to support one of our legacy applications which handled most mapping etc. with application logic.
Currently, I'm unable to configure this mapping with the given relationship instructions from EF Code First Fluent Configuration API, or at least I'm not sure how to do it. I tried mapping beginning from SetupGroup using WithMany, but here I can't declare that Camera and Display should be mapped on the CameraDisplayMap. Starting from CameraDisplayMap, I'm unable to declare the Id as being a foreign key to SetupGroup. Am I missing something?
CameraDisplayMap Class should be like following.
public class CameraDisplayMap {
public int Id { get; set; } //primary key
public int? SetupGroupId { get; set; } //foreign key to [SetupGroup]
public int? CameraId { get; set; } //foreign key to [Camera]
public int? DisplayId Displays { get; set; } //foreign key to [Display]
public virtual SetupGroup SetupGroups { get; set; }
public virtual Camera Cameras { get; set; }
public virtual Display Displays { get; set; }
}
I am using EF Model first to create two entities
public class Brief
{
public int Id { get; set; }
public string Title { get; set; }
public string tId {get; set;}
public int SpeakerId { get; set; }
}
public class Speaker
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
What I want to do is in Brief entity decorate tId field as Unique.
Second when I run entities as it is, it creates the database but it does not create foreigh key relation between SpeakerId in Briefs table and Speakers
Please let me know how
1. Decorate tId as unique
2. Why it is not creating the foreign key relation on SpeakerId and Speakers table?
Thanks
For problem number 2 you need to add a navigational property to your entity:
public class Brief
{
public int Id { get; set; }
public string Title { get; set; }
public string tId {get; set;}
public int SpeakerId { get; set; }
//Navigational property
public virtual Speaker Speaker { get; set;} 1 Brief has 1 Speaker
}
Depending on the Relationship this can also be public virtual ICollection<Speaker> Speakers { get; set;} Vice Versa for the Speaker entity:public virtual Brief Brief { get; set;} ` or the ICollection for n:m / 1:m relations
The unique constraint on non key columns should not be implemented as of yet based on http://entityframework.codeplex.com/workitem/299
Further reading / related questions:
Setting unique Constraint with fluent API?
http://bit.ly/OcE2HV
See Unique key with EF code first
Dependent on the EF version you can set an attribute on the property.
Use a navigational property so EF can determine the relation.
Note that the virtual keyword denotes lazy loading. See Entity Framework Code First Lazy Loading