2012-05-08 27 views
2

我使用ValueInjecter将视图模型平铺/解开为由实体框架(4.3.1)模型优先创建的域对象。我的数据库中的所有VARCHAR列都是NOT NULL DEFAULT ''(个人偏好,不希望在此打开圣战)。在发布后,视图模型会返回任何没有值为null的字符串属性,因此当我尝试将其注入到域模型类中时,EF咆哮着试图将IsNullable=false设置为null。例如(过简单):使用ValueInjecter将空字符串更改为string.Empty

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不这样做?

+0

Model-First or Code-First?如果Model-First或DB-First,您是否使用自定义T4?如果是这样或者你正在使用Code-First,那么你可以在属性的setter中添加一个空检查。 –

+0

@DannyVarod模型 - 第一,如问题所述,不使用自定义T4。我试图反映“TargetProp”的属性,并没有太大的了解。 –

+0

有些人把两者混为一谈。如果你使用默认的生成器T4,那么你的实体应该有一个基类。 –

回答

1

坚果,我只是在wiki的帮助下计算出来的。该解决方案似乎要延长UnflatLoopValueInjection

public class NullStringUnflatLoopValueInjection : UnflatLoopValueInjection<string, string> 
{ 
    protected override string SetValue(string sourceValue) 
    { 
     return sourceValue ?? string.Empty; 
    } 
}