自引用表实体框架插入记录
本文关键字:插入 记录 框架 实体 自引用 | 更新日期: 2023-09-27 18:21:08
无法确定相关操作的有效顺序。依赖项可能由于外键约束、模型要求或存储生成的值而存在
ASP.NET MVC3实体框架4.1
我的型号
public class OrganizationStructure
{
public OrganizationStructure()
{
this.OrganizationStructures = new List<OrganizationStructure>();
InputDate = DateTime.Now;
}
public int ID { get; set; }
public string Name { get; set; }
public int OrganizationStructureID { get; set; }
public int OrganizationID { get; set; }
public int OrganizationTypeID { get; set; }
public int OrganizationActivityID { get; set; }
public int OrganizationLocationID { get; set; }
public string AddRemark { get; set; }
public int UserId { get; set; }
public DateTime InputDate { get; set; }
public int? RemAttr { get; set; }
public IList<OrganizationStructure> OrganizationStructures { get; private set; }
}
表
ID int未选中
名称nvarchar(MAX)已检查
组织ID int已检查
OrganizationStructureID int未选中
OrganizationTypeID int已检查
OrganizationLocationID int已检查
OrganizationActivityID int已检查
AddRemark nvarchar(MAX)已检查
UserId int已检查
输入日期日期时间检查
RemAttr int已检查
public ICommandResult Execute(CreateOrUpdateOrganizationStructureCommand command)
{
var organizationStructure = new OrganizationStructure
{
ID = command.ID,
Name = command.Name,
OrganizationStructureID = command.OrganizationStructureID,
OrganizationID = command.OrganizationID,
OrganizationTypeID = command.OrganizationTypeID,
OrganizationActivityID = command.OrganizationActivityID,
OrganizationLocationID = command.OrganizationLocationID,
AddRemark = command.AddRemark,
UserId = command.UserId
};
if (organizationStructure.ID == 0)
_organizationStructureRepository.Add(organizationStructure);
else
_organizationStructureRepository.Update(organizationStructure);
_unitOfWork.Commit();
return new CommandResult(true);
}
OrganizationStructureID
属性必须可以为null,否则将无法插入具有自动递增主键的记录。
即使OrganizationStructureID
可以为null,EF也无法处理循环关系。您需要分两步保存它。
using (var scope = new TransactionScope())
{
var context = new MyContext();
var organizationStructure = new OrganizationStructure {/* assign props */ };
context.OrganizationStructures.Add(organizationStructure);
context.SaveChanges(); // step 1
organizationStructure.OrganizationStructures.Add(organizationStructure);
context.SaveChanges(); // step 2
scope.Complete();
}