문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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://docs.microsoft.com/pt-br/visualstudio/code-quality/ca2227?view=vs-2019

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top