我在使用Entity Framework 6的应用程序中遇到问题
我的一个EF实体是:
public class EmployeeHoliday
{
public EmployeeHoliday()
{
this.Employee = new Model.Employee();
}
public int HolidayId { get; set; }
public int EmployeeId { get; set; }
public byte HolidayTypeId { get; set; }
public string MasterEntity { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime RequestDate { get; set; }
public int CreatedBy { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool NonContinuous { get; set; }
public bool RequestInAdvance { get; set; }
public bool Authorized { get; set; }
public Nullable<int> AuthorizedBy { get; set; }
public DateTime? AuthorizedDate { get; set; }
public string AuthorizedNotes { get; set; }
public Nullable<int> DaysPending { get; set; }
public Nullable<int> DaysUsed { get; set; }
public Nullable<int> DaysApproved { get; set; }
public bool IsActive { get; set; }
public virtual Employee Employee { get; set; }
}
此实体与Employee
EF实体有关系,但我并未在所有情况下加载它。
现在我正在尝试插入一个新的EmployeeHoliday
,我收到一个错误,查看实体框架日志(在控制台中),我看到它正在尝试更新Employee
。< / p>
这就是我在做的事情:
// insert
var newRequest = new Model.EmployeeHoliday();
newRequest.EmployeeId = request.EmployeeId;
newRequest.MasterEntity = Uow.MasterEntity;
newRequest.CreatedBy = Uow.UserId;
newRequest.CreatedDate = DateTime.Now;
newRequest.Authorized = false;
newRequest.HolidayTypeId = request.HolidayTypeId;
newRequest.RequestDate = request.RequestDate;
newRequest.NonContinuous = !continuousDays;
newRequest.StartDate = dates.FirstOrDefault();
newRequest.EndDate = dates.LastOrDefault();
newRequest.RequestInAdvance = request.RequestInAdvance;
newRequest.IsActive = true;
Uow.HolidayRepository.Add(newRequest);
DbContext.SaveChanges();
控制台日志:
INSERT [dbo].[employee]([employerid], [memberid], [masterentity], [joindate], [employeenumber], [employeeformat], [leavedate], [leavetype], [credentialnumber], [employeetypeid], [employeegroupid], [jobtitleid], [profitcenterid], [locationid], [shiftcode], [timepolicyid], [holidaypolicyid], [overtimepolicyid], [supervisorid], [holidaytemplateid], [patterncode], [ispunishable], [isactive])
VALUES (@0, @1, NULL, @2, @3, NULL, NULL, NULL, NULL, NULL, @4, @5, @6, @7, NULL, @8, NULL, NULL, NULL, NULL, NULL, @9, @10)
SELECT [employeeid]
FROM [dbo].[employee]
WHERE @@ROWCOUNT > 0 AND [employeeid] = scope_identity()
我没有插入
Employee
,我正在插入EmployeeHoliday
所以,错误当然是:
Cannot insert the value NULL into column 'masterentity', table 'dbo.employee'; column does not allow nulls. INSERT fails.
我可以告诉EF不保存我的相关实体的任何线索吗?
答案 0 :(得分:0)
创建新的EmployeeHoliday
时,您还可以在构造函数中创建Employee
实例。
尝试将其设为null并查看它是否有效。
newRequest.EmployeeId = request.EmployeeId;
newRequest.Employee = null;