Entity Framework MapToStoredProcedures - Ignore Parameters

entity-framework entity-framework-6


We have a db table that has the following columns.

  • WidgetId (PK)
  • WidgetName
  • WidgetCreatedOn
  • WidgetLastUpdatedOn

We have stored procedures that handle the update/delete/insert on the Widget table.

The Insert stored proc takes just the WidgetName as the parameter e.g.

  exec Widget_Insert @WidgetName='Foo Widget'

Then the stored procedure puts the dates in for the WidgetCreatedOn WidgetLastUpdatedOn itself.

The Widget object has the same properties as the table e.g.

  • WidgetId (Key)
  • WidgetName
  • WidgetCreatedOn
  • WidgetLastUpdatedOn

Is it possible to tell the MapToStoredProcedures to ignore specific properties e.g.

            .MapToStoredProcedures(s =>
                s.Insert(i => i.HasName("Widget_Insert")
                      .Parameter(a => a.WidgetName, "WidgetName")
                      .Parameter(a => a.WidgetCreatedOn, **dont map it**)
                      .Parameter(a => a.WidgetLastUpdatedOn, **dont map it**)));

We are doing Code-First

1/29/2015 3:11:53 PM

Popular Answer

While there might be a way to manually change the MapToStoredProcedures configuration to do this, I have not uncovered it yet. Having said that, there is a way to accomplish this which I assume is how EF expects you to do things.

In your model mapping, specifying a DatabaseGeneratedOption of Identity or Computed will prevent that property from being sent to the insert proc.

If you think about it, this makes some sense. An insert proc will take as much information from the model as possible to do the insert. But an Identity/Computed property is one for which you're saying the DB will provide the data instead so it won't look to the model for that data.

A couple of things to note with this approach. EF will expect those Identity/Computed fields to come back from the proc so you'll need a select after the insert (filtering on SCOPE_IDENTITY() in sql server). EF also assumes that Identity fields won't come back as null, so those have to be Computed even if you don't intend them to be updated later.

If none of that seems palatable, the way to do this kind of thing in EF5 (and is a bit more flexible) is to override SaveChanges on the context and call the proc when the type is Widget and is EntityState.Added. Or you could throw an exception instead to force devs to call the proc on their own vs using EF's DBSet Add method.

3/2/2015 4:56:40 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow