我有3张桌子
员工(ID,FirstName,LastName) - 我们拥有所有员工,包括经理等。
EmployeeRole(RoleID,Role) - 这里我们定义了员工的角色
项目(ProjectName,Manager,Employee,Date ..) - 这里是分配给所有员工的项目的详细信息。
在项目表中,我有像Emmployee,Manager这样的列,这两列都是Employee表的外键。问题是我输入像(名字,姓氏),我如何找到emplyee的id。 或表结构是错误的?
当我尝试在项目表中插入数据时,EmployeeRole表也在更新。它不应该更新EMployeeRole表。它是一个主数据。
请建议我解决方案?
答案 0 :(得分:0)
您的逻辑数据模型不正确(恕我直言)。
项目可以有很多员工。员工可以将一个或多个项目作为特定角色工作。
因此,在Employee和Project之间有多对多,交集表具有Role类型。
e.g。
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
))
GO
CREATE TABLE [dbo].[Project](
[ProjectID] [int] NOT NULL,
[ProjectName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC
))
GO
CREATE TABLE [dbo].[ProjectEmployee](
[ProjectID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_ProjectEmployee] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC,
[EmployeeID] ASC,
[RoleID] ASC
))
GO
CREATE TABLE [dbo].[Role](
[RoleID] [int] NOT NULL,
[RoleName] [int] NOT NULL,
CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED
(
[RoleID] ASC
))
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Employee] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Project] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Project] ([ProjectID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Role] FOREIGN KEY([RoleID])
REFERENCES [dbo].[Role] ([RoleID])
GO
然后你的LinqToEntity看起来像这样:
// Add a new Role
Role role = new Role();
role.RoleID = 1; // TODO: make identity in database
role.RoleName = "Role 1";
db.Roles.Add(role);
db.SaveChanges();
// Add a new Employee
Employee employee = new Employee();
employee.EmployeeID = 1; // TODO: make identity in database
employee.FirstName = "Carl";
employee.LastName = "Prothman";
db.Employee.Add(employee);
db.SaveChanges();
// Add a new Project
Project project = new Project();
project.ProjectID = 1; // TODO: make identity in database
project.ProjectName = "Create new data model";
db.SaveChanges();
// Add employee to project as role1
ProjectEmployee projectEmployee = new ProjectEmployee();
projectEmployee.ProjectID = project.ProjectID;
projectEmployee.EmployeeID = employee.EmployeeID;
projectEmployee.RoleID = role.RoleID;
db.ProjectEmployees.Add(projectEmployee);
db.SaveChanges();