6

Lately, I've been working on enabling more of the Visual Studio code analysis rules in my projects. However, I keep bumping into rule CA2227: "Collection properties should be read only".

Say I have a model class like this:

public class Foo
{
    public string Name { get; set; }

    public List<string> Values { get; set; }
}

And I have a strongly-mapped view page:

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.Name)
    @Html.EditorFor(m => m.Name)
    for (int i = 0; i < Model.Values.Count; i++)
    {
        <br />
        @Html.LabelFor(m => Model.Values[i]);
        @Html.EditorFor(m => Model.Values[i]);
    }

    <button type="submit">Submit</button>
}

With ASP.NET MVC, I can write an action in my controller that will automatically bind this input to a class of type Foo:

[HttpPost]
public ActionResult ProcessForm(Foo model)
{
    return View(model);
}

The problem with this approach, is that my List<string> auto property violates rule CA2227. If I wasn't doing model binding, I could make the property read only and populate the collection elsewhere. However, that approach won't work with the default model binder. For now I've just been adding a suppression message when it occurs in a view model.

Is there a way I can bind a collection of items in a model without violating CA2227? Or is adding a suppression message my best option here?

2 Answers2

5

I believe you would need to create a custom ModelBinder to work around this, which isn't worth it. In this case since there's reasonable benefit to break the rule go ahead and suppress it.

STW
  • 44,917
  • 17
  • 105
  • 161
1

This is one one the cases that this rule should be suppressed as these model classes also perform work as transfer data object.

quoting the rule documentation:

When to suppress warnings

You can suppress the warning if the property is part of a Data Transfer Object (DTO) class.
Otherwise, do not suppress warnings from this rule.

https://learn.microsoft.com/pt-br/visualstudio/code-quality/ca2227?view=vs-2019

Community
  • 1
  • 1
Fernando Vieira
  • 3,177
  • 29
  • 26