2

I'm using ValueInjecter to flatten/unflatten view models into domain objects created by Entity Framework (4.3.1) model-first. All of my VARCHAR columns in my database are NOT NULL DEFAULT '' (personal preference, no desire to open up a holy war here). On post, the view model comes back with any string property that has no value as null, so when I attempt to inject it back into my domain model class, EF barks at me for attempting to set a property with IsNullable=false to null. Example (over-simple):

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
    }
}

Then, my controller post looks like this:

[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);
}

I'm using UnflatLoopValueInjection because I have nested types in the actual domain version of Thing. I attempted to write a custom ConventionInjection to convert null strings to string.Empty, but it appears that UnflatLoopValueInjection switches it back to null. Is there a way I can get ValueInjecter not to do this?

AJ.
  • 16,368
  • 20
  • 95
  • 150
  • Model-First or Code-First? If Model-First or DB-First, are you using a custom T4? If so or you are using Code-First, then you could add a null check into the properties' setters. – Danny Varod May 08 '12 at 17:04
  • @DannyVarod model-first, as stated in the question, not using a custom T4. I attempted to reflect the attributes of the `TargetProp` and didn't get very far with that. – AJ. May 08 '12 at 17:05
  • some people confuse the two. If you are using the default generator T4s, then your entity should have a base class. – Danny Varod May 08 '12 at 17:11

1 Answers1

1

Nuts, I just figured it out with help from the wiki. The solution appears to be to extend UnflatLoopValueInjection:

public class NullStringUnflatLoopValueInjection : UnflatLoopValueInjection<string, string>
{
    protected override string SetValue(string sourceValue)
    {
        return sourceValue ?? string.Empty;
    }
}
AJ.
  • 16,368
  • 20
  • 95
  • 150