How to effectively implement 1 to many relationship? - c#

I have an EF model to is connected 1 to 1 for many tables but I am having trouble connecting a 1 to many table. Currently using EF6 on .Net 4.8. The error I am recieving is "Multiplicity is not valid in Role '' in relationship 'Login_Users'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'"
The main table is
Users
public partial class Users
{
public Users()
{
this.Login = new HashSet<Login>();
this.Phone = new HashSet<Phone>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public System.DateTime BirthDate { get; set; }
public int LastFourSSN { get; set; }
public Nullable<int> AddressId { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Login> Login { get; set; }
public virtual ICollection<Phone> Phone { get; set; }
}
One to one tables
public partial class Login
{
public Login()
{
this.Login_Track = new HashSet<Login_Track>();
this.Policy = new HashSet<Policy>();
}
public string Username { get; set; }
public string Password { get; set; }
[Key, ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> LastLoginDate { get; set; }
public virtual Users Users { get; set; }
}
Address
public partial class Address
{
public Address()
{
this.Users = new HashSet<Users>();
}
[Key, ForeignKey("Users")]
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public virtual ICollection<Users> Users { get; set; }
}
1 to many table
public partial class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Number { get; set; }
public string Type { get; set; }
[ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public virtual Users Users { get; set; }
}

Related

Entity Framework accessing data within include and .thenInclude

I am new to Entity Framework.
I understand the basics but am a little confused here.
await Context.PremiseContacts
.Include(c => c.Contact)
.ThenInclude(c => c.ContactEmails)
So imagine I have this code.
Contact is within premise contacts and then contact emails is within contact.
How would I access the contact emails data ?
I have tried this
Email = c.Contact.ContactEmails.,
when passing on the model but that is much options as I get and there should be more properties within contact email.
Essentially how do you access the data defined by .include and then how would you access the data defined by multiple includes/ then includes.
EDIT
Premise Contact
namespace SolaceSecure.DAL.Models
{
[Table("premiseContact")]
public partial class PremiseContact
{
[Key]
[Column("premiseId")]
public Guid PremiseId { get; set; }
[Key]
[Column("contactId")]
public Guid ContactId { get; set; }
[Column("isSolaceUser")]
public bool? IsSolaceUser { get; set; }
public virtual Contact Contact { get; set; }
public virtual Premise Premise { get; set; }
}
}
Contact
public Contact()
{
ContactEmails = new HashSet<ContactEmail>();
ContactPhoneNumbers = new HashSet<ContactPhoneNumber>();
PremiseComplianceContacts = new HashSet<PremiseComplianceContact>();
PremiseContacts = new HashSet<PremiseContact>();
}
[Key]
[Column("contactId")]
public Guid ContactId { get; set; }
[Required]
[Column("contactName")]
[StringLength(100)]
public string ContactName { get; set; }
[Column("contactDescription")]
[StringLength(250)]
public string ContactDescription { get; set; }
[Column("customerId")]
public Guid CustomerId { get; set; }
[Column("userId")]
public Guid? UserId { get; set; }
[Column("dateCreated", TypeName = "datetime")]
public DateTime DateCreated { get; set; }
[Column("dateModified", TypeName = "datetime")]
public DateTime? DateModified { get; set; }
[Column("modifiedBy")]
public Guid? ModifiedBy { get; set; }
[Column("isDeleted")]
public bool IsDeleted { get; set; }
[Column("createdBy")]
public Guid? CreatedBy { get; set; }
public virtual Person CreatedByNavigation { get; set; }
public virtual Customer Customer { get; set; }
public virtual Person ModifiedByNavigation { get; set; }
public virtual Person User { get; set; }
public virtual ICollection<ContactEmail> ContactEmails { get; set; }
public virtual ICollection<ContactPhoneNumber> ContactPhoneNumbers { get; set; }
public virtual ICollection<PremiseComplianceContact> PremiseComplianceContacts { get; set; }
public virtual ICollection<PremiseContact> PremiseContacts { get; set; }
Contact Email
{
[Table("contactEmail")]
public partial class ContactEmail
{
[Key]
[Column("contactEmailId")]
public Guid ContactEmailId { get; set; }
[Required]
[Column("email")]
[StringLength(100)]
public string Email { get; set; }
[Column("contactId")]
public Guid ContactId { get; set; }
[Column("emailTypeId")]
public Guid EmailTypeId { get; set; }
public virtual Contact Contact { get; set; }
}
}

How to use identity aspnetusers

I asked a question earlier but I don't think I asked it correctly.
in my asp.net mvc application I am using aspnetusers for my login and registration.
If I have another model for Employees containing their information, How do I connect these two models so when a user logs in, it grabs their information from the employee table to be used. I created the Employees Model with sql server and used ado.net entity data model to use it in visual studio.
Employee Model:
public partial class Employee
{
public int UserID { get; set; }
[Key]
public int EmployeeID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public System.DateTime StartDate { get; set; }
public int RoleID { get; set; }
public int ShiftID { get; set; }
public int AreaID { get; set; }
public int DisciplineID { get; set; }
public int SiteID { get; set; }
public int ALCategory { get; set; }
public int HoursTaken { get; set; }
public Nullable<int> AwardedLeave { get; set; }
public Nullable<int> TotalHoursThisYear { get; set; }
public int HoursCarriedForward { get; set; }
public Nullable<int> EntitlementRemainingThisYear { get; set; }
public string Comments { get; set; }
public int SickLeaveTaken { get; set; }
public Nullable<int> SickLeaveEntitlement { get; set; }
public Nullable<int> SickLeaveEntitlementRemaining { get; set; }
public int StudyLeaveEntitlement { get; set; }
public int StudyLeaveTaken { get; set; }
public Nullable<int> StudyLeaveRemaining { get; set; }
public int ExamLeaveTaken { get; set; }
public int ForceMajeure { get; set; }
public int BereavementLeaveTaken { get; set; }
public int MaternityLeaveTaken { get; set; }
public int ParentalLeaveTaken { get; set; }
public int AdoptionLeaveTaken { get; set; }
public string ManagerEmail { get; set; }
public string AreaManagerEmail { get; set; }
public virtual Area Area { get; set; }
public virtual Discipline Discipline { get; set; }
public virtual Shift Shift { get; set; }
public virtual Site Site { get; set; }
public virtual Employee Employee1 { get; set; }
public virtual Employee Employee2 { get; set; }
}
And the log-in model:
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
So can I connect these two?
Does it matter that I use database first model?
Could I use a Foreign Key to connect by email?
I want to use it for example to filter a table of employees to only show the employees who have the same siteID for the user logged in.
So when a user logs in, I want them to only see employees with the same site as themselves on the employee HTML table.
After successful login, you will get Id of AspNetUser. Take foreign key reference of column Id from AspNetUser table in your Employee table. By doing this, you can achieve expected result. Simply one more thing you need to add in your Employee model as mentioned below:
public virtual ApplicationUser ApplicationUser { get; set; }

Entity Framework Relationships two tables

I'm trying to create a Friendship mapping table that has 2 FK's that originate from the same class (User and SportsFacility)
Here are my model classes.
public partial class User
{
[Key]
public int Id { get; set; }
[Required]
public int AcountId { get; set; }
[Required]
[MaxLength(20)]
//[Column(TypeName = "varchar")]
public string Login { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvents { get; set; }
}
public partial class SportsFacility
{
public SportsFacility()
{
ChecksQueue = new List<CheckQueue>();
BookedEvent = new List<BookedEvent>();
}
[Key]
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public int PnH_Id { get; set; }
[Required]
[MaxLength(70)]
public string Address { get; set; }
public int City_Id { get; set; }
[ForeignKey("City_Id")]
public virtual City City { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvent { get; set; }
}
public partial class CheckQueue
{
[Key]
public int Id { get; set; }
public DateTime StartCheckTime { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
[Index]
public DateTime? LastCheck { get; set; }
}
public partial class BookedEvent
{
[Key]
public int Id { get; set; }
public DateTime BookDate { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
}
I tried override the OnModelCreating method in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<City>();
modelBuilder.Entity<SportsFacility>();
modelBuilder.Entity<User>();
modelBuilder.Entity<CheckQueue>();
modelBuilder.Entity<BookedEvent>();
base.OnModelCreating(modelBuilder);
}
This causes a new error message to be displayed.
Additional information: The entity types 'BookedEvent' and 'CheckQueue' cannot share table 'CheckQueues' 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.
Any help would be greatly appreciated.

Entity Framework 6 asp.net Code First Setup

Hi guys I am spinning wheels on this one. I am using EF6 and ASP.Net 4.6. I have a given table which has student information and parent information. A student can have many parents and a parent can have many students. Call this table 'Contact'. I am to create a table called 'Request' which will hold information for a parent submitting a request for his student. I will create a lookup table with two columns, one for student id and one for parent id called 'StudentParents'. I want to be able to have the parent log in, select his student from a drop down of all of his students and submit the request. The many to many relationship is throwing me off as far as my include statements. How can I get EF to set up this structure so that when I GetRequest(id) I can get the Student info and the Parent info to be included? Here is my code that wont Include anything other than the request.
public class Contact
{
[Key]
public int id { get; set; }
public string student_id { get; set; }//This is the Student ID
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public string grade { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_first_name { get; set; }
[Display(Name = "Parent Middle Name")]
public string contact_middle_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
[Display(Name = "Parent Email")]
public string contact_email { get; set; }
[Display(Name = "Parent Address")]
public string login { get; set; }//This is the Parent ID
public string Classif_description { get; set; }
}
public class Request
{
[Key]
public int id { get; set; }
public Student student_id { get; set; }
public Contact login { get; set; }
[Display(Name = "First School Choice")]
public string firstSchool { get; set; }
[Display(Name = "Second School Choice")]
public string secSchool { get; set; }
[Display(Name = "Rising Grade")]
public string rising_grade { get; set; }
public DateTime ReqSubmitted { get; set; }
public string ReqStatus { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public string ModifBy { get; set; }
}
public class Parent
{
public int id { get; set; }
public string contact_first_name { get; set; }
public string contact_middle_name { get; set; }
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
public string contact_email { get; set; }
public string contact_address { get; set; }
public string contact_city { get; set; }
public string contact_zip { get; set; }
[Key]
public string login { get; set; }
public string contact_pw { get; set; }
public string phone { get; set; }
public string phone_type { get; set; }
public Parent() { }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public int id { get; set; }
public int student_id { get; set; }
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public DateTime birthdate { get; set; }
public string gender { get; set; }
public string grade { get; set; }
public string Fed_race_description { get; set; }
public string Classif_description { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
public int home_school_id { get; set; }
public string home_school_name { get; set; }
public Student()
{
this.Parents = new HashSet<Parent>();
}
public virtual ICollection<Parent> Parents { get; set; }
}
public class OEContext : DbContext
{
public OEContext() : base("name=OEContext")
{
}
public DbSet<Request> Requests { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.HasMany(s => s.Students)
.WithMany()
.Map(x =>
{
x.MapLeftKey("login");
x.MapRightKey("student_id");
x.ToTable("StudentParents");
}
);
base.OnModelCreating(modelBuilder);
}
}
Changed the strategy. Made Request have many Contacts. So I added a constructor to the request:
public Request()
{
Contacts = new List<Contact>();
}
public virtual ICollection<Contact> Contacts { get; set; }
Next I changed the contact class:
public int ContactId { get; set; }
public Contact() { }
public virtual Request Request { get; set; }
With this relationship I can pull both Parents and a student from the Contacts associated with the Request.

How to properly add a foreign key from my own model to the EF Userprofile?

my model classes first:
public class Person
{
[Required, Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile profile { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public Nullable<int> ID { get; set; }
public virtual Person personprofile { get; set; }
}
when i run this however it gives me this exception: The principal end of this association must be explicitly configured
i've searched this error but it doesn't clarify it for me... so i absolutely have no clue how to fix this. Basically i want to link my Person class to the Userprofiles so that i can create a login mechanism that automatically lets 1 person who makes an account on the site get 1 Profile to Edit to his own information. He's however not allowed to modify other people their accounts.
I hope this makes my problem clear and that somebody can help me :). i'm using EF 6 btw and i get the error in the class InitializeSimpleMembershipAttribute that comes standard with the MVC example of ASP.net
Greetings and thanks in advance,
Marijn
I managed to get it working with these codes in the models:
[Table("UserProfile")]
public class UserProfile
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual Person personprofile { get; set; }
}
public class Person
{
[ForeignKey("profile"), Key]
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public UserProfile profile { get; set; }
}

Categories

Resources