简体   繁体   中英

What is the Best practice for implementing a 'many' navigation property in EF Core

So I have this growing amount of database models using List<T> for their 'many' navigational properties. An example could be this:

public class ResourceType
{
    public int ResourceTypeId { get; set; }
    public string Name { get; set; }
    public List<Resource> Resources { get; set; }
}

I was reading about good habits when doing C# was to avoid ever returning null rather than an empty list. I can think of a couple of ways to accomplish this.

public List<Resource> Resources { get; set; } = new List<Resource>();

or perhaps even by doing:

private List<Resource> _Resources { get; set; }
public List<Resource> Resources {
    get {
        if (_Resources == null) {
            _Resources = new List<Resource> ();
        }
        return _Resources;
    }
    set {
        _Resources = value;
    }
}

In other places people recommend using ICollection<T> and how would one prevent this from returning null?

Meanwhile the rule of thumb when designing EF models, is that the model should represent the table as closely as possible. Does this rule break either of the above examples?

All of this leads me to one question: What is the best way of handling this type of property? What type should be used, and should it be prevented from returning null? and what is the best case to prevent that in this type of situation?

My answer would be to do it this way:

public ICollection<Resource> Resources { get; set; } = new List<Resource>();

And regarding type. You should probably not be using List as the declared type of the property, I would say that best practice is to declare these properties with interfaces (you might want to change the actual instance class at some point). Furthermore don't expose more methods in the list/collection/enumerator then what you absolutely need. In most cases ICollection or IEnumerable is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM