【发布时间】:2013-07-31 21:17:00
【问题描述】:
正如实体框架所说,“代码优先”,这里我们先使用代码......
public class BaseModel
{
[Key]
public Guid Id { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateChanged { get; set; }
public BaseModel()
{
this.Id = Guid.NewGuid();
this.DateCreated = DateTime.Now;
this.DateChanged = DateTime.Now;
}
}
public class Association: BaseModel
{
public string Name { get; set; }
public string Type { get; set; }
public virtual List<Rule> Rules { get; set; }
public Association()
: base()
{
}
}
public class Rule: BaseModel
{
[ForeignKey("Association")]
public Guid AssociationId { get; set; }
//[Required]
public virtual Association Association { get; set; }
//[Required]
public string Name { get; set; }
public string Expression { get; set; }
public virtual List<Action> Actions { get; set; }
public Rule()
: base()
{
}
}
public class Action: BaseModel
{
public string Name { get; set; }
public string ActionType { get; set; }
[ForeignKey("Rule")]
public Guid RuleId { get; set; }
public virtual Rule Rule { get; set; }
public int Order { get; set; }
public Action()
: base()
{
}
}
所以这是我首先使用实体框架代码的四个模型类。 每个都继承自基类,因此它们都有一个 Id Guid 作为主键。
一个协会有一个规则列表。 (规则对协会有 FK) 具有操作列表的规则。 (Action 有 FK to Rule)
我想做的只是改变并保存最上面的 class= 关联。 例如,在删除规则时,我希望这段代码能够工作:
public ActionResult DeleteRule(Guid assId, Guid ruleId)
{
Association ass = this.DataContext.Associations.FirstOrDefault(a => a.Id == assId);
ass.Rules.RemoveAll(r => r.Id == ruleId);
this.DataContext.SaveChanges();
return RedirectToAction("Index");
}
在 context.savechanges 这给了我这个错误: '操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。'
删除操作时也会出现此错误。
有没有办法改变最上层(关联)对象并且只改变这个关联的东西。 我不想说 context.Rules.remove(...) 或 context.actions.remove(...)
来源:http://server.thomasgielissen.be/files/mvctesting.zip 您需要 VS2012,所有 nuget 包都包含在 zip 中,您应该能够构建和运行该项目。
提前感谢您的反馈!
问候, 托马斯
【问题讨论】:
-
你需要重新格式化这个问题。简化您的问题描述,并在帖子中包含最少的相关代码。就目前而言,您不太可能获得帮助。
-
问题更新了!,希望我现在得到帮助:)
标签: asp.net-mvc-4 ef-code-first entity-framework-5