Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework MapToStoredProcedures - Ignore Parameters

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.

        modelBuilder.Entity<Widget>()
            .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

like image 406
ASG Avatar asked Jan 29 '15 15:01

ASG


1 Answers

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.

like image 155
ShawnFumo Avatar answered Oct 02 '22 06:10

ShawnFumo