I'm using the database first implementation of Entity Framework Code First as the data layer for a project, but I've run into a problem.
I need to be able to set a foreign key to null in order to remove an association in the database.
I have 2 objects. One is called Project.
public class Project
{
public int ProjectId {get; set;}
public Employee Employee {get;set;}
}
public class Employee
{
public int EmployeeId {get; set;}
public string EmployeeName {get;set;}
}
This matches what I have in the Database:
CREATE TABLE Project(
ProjectId int IDENTITY(1,1) NOT NULL,
EmployeeId int NULL
)
CREATE TABLE Project(
EmployeeId int IDENTITY(1,1) NOT NULL,
EmployeeName varchar(100) NULL
)
I can assign an Employee to a project. However, I want to be able to remove an employee from a project and have the Employee field be null. In my UI this will show as 'No EMployee Assigned'.
However, short of a direct sql query, I cannot seem to find a way to do this in the entity framework 4.1.
I've tried:
public void RemoveEmployeeFromProject(int projectId)
{
var project = Context.Projects.FirstOrDefault(x => x.ProjectId == projectId);
project.Employee = null;
Context.SaveChanges();
}
But this doesn't do anything.
Does anyone have any ideas?
question from:
https://stackoverflow.com/questions/6420976/setting-a-foreign-key-to-null-when-using-entity-framework-code-first 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…