4

Auto-generated action methods in MVC5 make use of the BindAttribute with an Include list that contains the field names in a string literal.

Example:

// POST: MyTable/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, 
//   for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Field1, Field2, Field3")] MyEntity myEntity)
{
    ... 
}

If Field1 is renamed in MyEntity, it will not automatically be updated in the Include list. If the developer forgets to update the Include lists, the compiler will not complain and the issue might not be discovered until runtime.

I understand that it is common to use view-model classes and a tool such as AutoMapper to map between view-model and domain-model, and it is then easy to create unit tests for those mappings to catch rename errors.

However, if the action method is using the domain-model directly and using a Bind Include list as shown above, is there a way to create a unit test to test the model binding and catch a rename error?

2

I've worked on and continue to work on large scale api projects and I've never used the BindAttribute. I would say with this code remove it completely, it will still work and it will remove the error prone strings in the attribute.

Personally and from my experiences you shouldn't pass out your data entities from an api endpoint.

We use view models, but call them DataContract, like CarDataContract, HouseDataContract etc. Then as you mentioned we use AutoMapper to map view model to domain model.

From there (as long as you've written it well) you can then test your controllers, the mappings and the domain all in splendid isolation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.