How to design one to many relationship in efcore? - c#

Hi I am working on entity framework core. I have user table and user may be part of multiple projects. And user for each project has to enter time sheet data. For example below is my user table.
public class User
{
[Key]
public string Id { get; set; }
public string name { get; set; }
public string emailId { get; set; }
}
Below is my project table.
public class Project
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public string userId { get; set; }
}
Here User may belong to multiple projects. Now for each project user has to enter timesheet data. Below is timesheet table.
public class TimeSheetData
{
[Key]
public string id { get; set; }
public string project_id { get; set; }
public string hours_logged { get; set; }
}
I have to define this in entity framework core. One user may be part of multiple projects and user needs to enter data to timesheet for each project. How can I define relationship with respect to above table?
In user table Do I need to add something like Public List<Project> Projects? Also In Project table Public List<Timesheet> Timesheets something I have to define here. Can some one help me to understand this? Any help would be greatly appreciated. Thanks

Assuming you will be changing string to int ids, does something below work?
public class User
{
public User()
{
this.Projects = new HashSet<Project>();
}
[Key]
public int Id { get; set; }
public string name { get; set; }
public string emailId { get; set; }
public virtual ICollection<Project> Projects { get; set;}
}
public class Project
{
public Project()
{
this.TimeSheetData = new HashSet<TimeSheetData>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int userId { get; set; }
[ForeignKey("userId")]
public virtual User User {get; set; }
public virtual ICollection<TimeSheetData> TimeSheetData { get; set;}
}
public class TimeSheetData
{
[Key]
public int id { get; set; }
public int project_id { get; set; }
[ForeignKey("project_id")]
public virtual Project Project {get; set; }
public string hours_logged { get; set; }
}

Related

C# Entity Framework - Entity only relating to one entry at a time

So I am have difficulty understanding why CompaniesAccepted is only allowing one Company to be related at a time.
So for example if I have 2 entries of File in my Database. The company then accepts one of these files and gets added to CompaniesAccepted list. If I try to add this same company to the other File entry, the Company will be removed from the CompaniesAccepted list from the first file and added to the list of the new one which doesn't make sense to me as I wish to have the Company in both of those lists.
public class File
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual Company Company { get; set; }
public string DisplayName { get; set; }
public virtual List<Company> CompaniesAccepted { get; set; }
public bool isDeleted { get; set; }
}
Company Entity
public class Company
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public string ParentCompany { get; set; }
public string CompanyName { get; set; }
public string LegalName { get; set; }
public string DUNS { get; set; }
[JsonIgnore]
public virtual Company CustomerCompany { get; set; }
public bool isActivated { get; set; }
public bool isDeleted { get; set; }
}
Code used to add the relationship.
if(accepted)
{
var company = file.CompaniesAccepted.FirstOrDefault(x => x.Id == account.Company.Id);
if(company == null)
{
file.CompaniesAccepted.Add(account.Company);
}
} else
{
file.CompaniesAccepted.Remove(account.Company);
}
Db.SaveChanges();
Any suggestions? If I haven't provided enough code, please do ask.

Entity Framework many to many to single object

I am trying to map a property on a user that that has a many to many relationship in the database but there is only ever one per user. But I am unable to figure out the required map in entityframework. I have the following entities:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//Need to map this property
public virtual SecurityRole SecurityRole { get; set; }
}
public class SecurityRole
{
public int Id { get; set; }
public string Name { get; set; }
}
An the following tables:
User:
Id
FirstName
LastName
SecurityRole:
Id
Name
UserSecurityRole:
UserId
SecurityRoleId
If anyone has any idea or could point me in the right direction that would be great
Even if there is only one record in the database, if you have a many to many relationship between User and SecurityRole it should work like this:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<SecurityRole> SecurityRoles { get; set; }
}
public class SecurityRole
{
public int Id { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
}

EF code Model for e-tender system in MVC4

Am building tender board Application am getting some confusing in how structure my model using >> entity-framework in >> MVC4
Here the descriptions:
In my simple membership Role Table , I have:
(Admin,Tender,Provider,Member)
Administration: he have right to change normal user role from “Member” to “Provider and prove winner bidder after tender organization approved.
Suppliers: Normal users will be assigning as “member” and will be activated by Administration to be provider and then they can bid any projects they want.
Projects: created by Tender Organization Users every project has many requirements
Requirement: each one related to project.
Tenders: Here my problem actually Tender are “Ministries in country and have to be set in system” but each ministry obvious have many users “Manager, let say 5 in each” who will vote for supplier.Mangers can vote to only those suppliers which are laid under the same ministry.
Do I miss others tables?
Also I don’t really know how to structure all the tables with relations and also with (UserprofileTbale, and Role Table):
Here my try, help me on that.
My DBContext:
public class ProjectContext : DbContext
{
public ProjectContext()
: base("OTMSProjects")
{
}
public DbSet<ProjectEntry> Entries { get; set; }
public DbSet<Requiernments> RequiernmentEntries { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Tender> Tenders { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
//public DbSet<UserRoles> UserRoles { get; set; } // do I have to set this too?
}}
My tables:
public class ProjectEntry
{
[Key]
public int ID { get; set; }
[Required]
public string ProjectName { get; set; }
public string Description { get; set; }
public string Statue {get; set; }
public string UplodedFiles { get; set; }
public string Budget { get; set; }
public string EstimateTime { get; set; }
public string Criterias { get; set; }
public DateTime? DueDate { get; set; }
// Relations with others tables
public virtual Tender Tender { get; set; }// every project have only one tender
public virtual ICollection<Supplier> Suppliers { get; set; } // every project have one or more supplier
public virtual ICollection<Requiernments> Requirements { get; set; }
}
........
public class Requiernments
{
[Key]
public int RequiernmentId { get; set; }
public int ID { get; set; }
public string RequiernmentName { get; set; }
public string RequiernmentType { get; set; }
public string RequiernmentPrioritet { get; set; }
public float RequiernmenWhight { get; set; }
public string ProviderAnswer { get; set; }
public string ProviderComments{ get; set; }
public virtual ProjectEntry Projects { get; set; }
}
........
public class Supplier
{
[Key]
public int SupplierId { get; set; }
public int ID { get; set; }
public int SupplierName { get; set; }
public int SupplierCat { get; set; }
public virtual ICollection<ProjectEntry> Projects { get; set; }
}
......
public class Tender
{
[Key]
public int TenderId { get; set; }
public string TenderName { get; set; }
public string TenderMinstry{ get; set; }
public int ID { get; set; }//link to project
public int UserId { get; set; } //this links to the userid in the UserProfiles table
public virtual ICollection<ProjectEntry> Projects { get; set; }
//public virtual ICollection<UserProfile> Userprofile { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
My membership table in my AccountModel created by defualt in Mvc4 ( I only add the RoleTable :
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public ICollection<UserRoles> UserRoles { get; set; }
}
[Table("webpages_Roles")]
public class UserRoles
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
[ForeignKey("UserId")]
public ICollection<UserProfile> UserProfiles { get; set; }
}
Am not sure also about how to link the Userprofile with Tender Table and supplier Table?
Not sure what you are missed or not. but as per database creation you must follow your business logic and normalization rules.
Some of my suggestions are here:
1. ProjectEntry
here you should create a Status Table separately and gives its reference key as StatusID into the ProjectEntry table.
Requirement
you should create Requirement Priority and Type tables are separately.
Add separate table for provider question and answers. I hope you need to store more than one question answers for single requirement.
Supplier
Add Separate Table for Supplier category
Tender
Create Tender Ministry table separately and give its reference to the tender table.
you should make a table for Uploaded files as Documents. It should contains ID, ProjectId, Documentname, DocumentType, DocumentShortDescription, uplodatedDateTime fields.

Entity Framework Code First Relationships

I'm learning EF using Code First and I'm having a lot of trouble getting my relationships to build correctly.
A Simple Employee
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
}
A Simple Project
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
}
The time spent on the project
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public String ProjectID { get; set; }
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
I'm trying to join Employee to Time on EmployeeID and join Project to Time on ProjectID and I just don't understand how EF determines relationships. I'm trying to use Data Annotations to define the relationships. I've tried using the ForeignKey annotation to define the relationships but that has not worked either.
What I have will run, but on the Project table, a new field named Project_ProjectID is created and if I try to run a query in VS I get an error saying that the column Time_TimeID is invalid (which it is). What am I doing wrong?
You shouldn't need DataAnnotations as conventions will work for you in this case
Try the following
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public int ProjectID { get; set; } //<< Changed type from string
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
This article may help
http://msdn.microsoft.com/en-gb/data/jj679962.aspx

Entity Framework - Store parent reference on child relationship (one -> many)

I have a setup like this:
[Table("tablename...")]
public class Branch
{
public Branch()
{
Users = new List<User>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
}
[Table("tablename...")]
public class User
{
[Key]
public int Id {get; set; }
public string Username { get; set; }
public string Password { get; set; }
[ForeignKey("ParentBranch")]
public int? ParentBranchId { get; set; } // Is this possible?
public Branch ParentBranch { get; set; } // ???
}
Is it possible for the User to know what parent branch it belongs to? The code above does not populate the ParentBranch.
Entity Framework version 5.0
.NET 4.0
c#
Try making navigation properties virtual,
[Table("tablename...")]
public class Branch
{
public Branch()
{
Users = new List<User>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual List<User> Users { get; set; }
}
[Table("tablename...")]
public class User
{
[Key]
public int Id {get; set; }
public string Username { get; set; }
public string Password { get; set; }
[ForeignKey("ParentBranch")]
public int? ParentBranchId { get; set; } // Is this possible?
public virtual Branch ParentBranch { get; set; } // ???
}

Categories