【发布时间】:2012-05-08 16:55:03
【问题描述】:
我正在使用 ValueInjecter 将视图模型展平/取消展平为由实体框架 (4.3.1) 模型优先创建的域对象。我数据库中的所有VARCHAR 列都是NOT NULL DEFAULT '' (个人喜好,不想在这里开启一场圣战)。在发布后,视图模型返回任何没有值为 null 的字符串属性,因此当我尝试将其注入我的域模型类时,EF 对我咆哮,因为我试图将带有 IsNullable=false 的属性设置为 null。示例(过于简单):
public class ThingViewModel
{
public int ThingId{get;set;}
public string Name{get;set;}
}
public class Thing
{
public global::System.Int32 ThingId
{
//omitted for brevity
}
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Name
{
//omitted for brevity
}
}
然后,我的控制器帖子如下所示:
[HttpPost]
public ActionResult Edit(ThingViewModel thing)
{
var dbThing = _thingRepo.GetThing(thing.ThingId);
//if thing.Name is null, this bombs
dbThing.InjectFrom<UnflatLoopValueInjection>(thing);
_thingRepo.Save();
return View(thing);
}
我使用UnflatLoopValueInjection 是因为我在Thing 的实际域版本中有嵌套类型。我尝试编写自定义ConventionInjection 将空字符串转换为string.Empty,但似乎UnflatLoopValueInjection 将其切换回空字符串。有没有办法让 ValueInjecter 不这样做?
【问题讨论】:
-
模型优先还是代码优先?如果是 Model-First 或 DB-First,您使用的是自定义 T4 吗?如果是这样,或者您使用的是 Code-First,那么您可以在属性的设置器中添加一个空检查。
-
@DannyVarod 模型优先,如问题中所述,不使用自定义 T4。我试图反映
TargetProp的属性,但并没有走得太远。 -
有些人混淆了这两者。如果您使用的是默认生成器 T4s,那么您的实体应该有一个基类。
标签: asp.net-mvc entity-framework valueinjecter