Consider following class
public class AccountGroup : Entity<int>
{
public AccountGroup()
{
Accounts = new HashSet<Account>();
Groups = new HashSet<AccountGroup>();
}
// option 1 - read only properties
public bool IsRoot { get { return Parent == null; } }
public bool IsLeaf { get { return !Groups.Any(); } }
public Account MainAccount { get { return Accounts.FirstOrDefault(a=>a.Type == AccountType.MainAccount); } }
// option 2 - parameter-less methods
//public bool IsRoot() { return Parent == null; }
//public bool IsLeaf() { return !Groups.Any(); }
//public Account GetMainAccount() { return Accounts.FirstOrDefault(a => a.Type == AccountType.MainAccount); }
public string Name { get; set; }
public string Description { get; set; }
public virtual ISet<Account> Accounts { get; private set; }
public virtual ISet<AccountGroup> Groups { get; private set; }
public virtual AccountGroup Parent { get; set; }
}
If I want to “enrich” the class above, which option approach should I use.
Option 1
Should I use read only parameters knowing that EF does not like them (trying to use IsRoot in Where clause throws ex, with The specified type member 'IsRoot' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Option 2
Or should I go with parameter-less methods (not sure what would be disadvantages)
In general (not considering EF), which approach is preferred considering above when functionality is equivalent (i.e. I get the same functionality if I invoke .IsRoot or .IsRoot())
IsRootfeels more like a property to me. It represents current state of the object, doesn’t actually do anything when invoked other than report that state, and generally getters/setters in .NET are properties.There are other things to consider, a JSON/XML serializer will not serialize
IsRoot()but will forIsRootas a property. Generally speaking a lot of things in .NET hinge off of properties, so often they are the better choice.EF wouldn’t like
IsRoot()either, it just doesn’t know how to translate IsRoot into SQL, whether it’s a property or method.