无法确定相关操作的有效排序。由于外键约束,模型要求或存储生成的值,可能存在依赖关系。
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)已选中
OrganizationID int Checked
OrganizationStructureID int未选中
OrganizationTypeID int Checked
OrganizationLocationID int Checked
OrganizationActivityID int Checked
AddRemark nvarchar(MAX)选中
UserId int已选中
InputDate datetime已检查
RemAttr int Checked
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);
}
答案 0 :(得分:0)
OrganizationStructureID
属性必须是可空的,否则您将无法使用自动递增的主键插入记录。
OrganizationStructureID
可空,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();
}