简体   繁体   中英

Multiple nullable Guid and only one of them can have a value

I have a FinancialAccount Class that can be linked into three other classes, or manually generated , So I implemented one Enum holding the the type of class that its linked to and three other nullable Guid's to hold the Guid of that linked class

public enum AccountClassificaiton
{
    Normal,
    Bank,
    Contract,
    Employee,
}

public Account()
{
    ...
    public Guid Id { get; set; }
    public string Name { get; set; }
    public AccountClassificaiton AccountClassificaiton { get; set; }
    public Guid? ContractId { get; set; }
    public Guid? EmployeeId { get; set; }
    public Guid? BankAccountId { get; set; }
    ...
}

I need a better approach for this problem considering that i cant move these Guids out of this class , and there is a relation of one to one between this class and those three classes , and only one of these Guid should have a value depending on what AccountClassification this class has

Sorry for my English, I'm not a native speaker

Edit-1

Im using a Domain-Driven-Design pattern with 8 projects on the same solution so its not easy for me to show you the real problem without having a legal problem

Edit-2

This project is a part of Financial Management system which is a part of a huge ERP system

I would design it differently:

public enum AccountClassificaiton
{
    Normal,
    Bank,
    Contract,
    Employee,
}

public Account()
{
    ...
    public Guid Id { get; set; }
    public string Name { get; set; }
    public AccountClassificaiton AccountClassificaiton { get; set; }
    public List<Account> LinkedAccounts { get; set; }
    ...
}

Something like that.

Or, even better in case you need to find linked accounts fast by the account type, you can use a Dictionary where the key is the AccountClassificaiton type (value is the Account object) to group the linked accounts by type:

public Dictionnary<AccountClassificaiton, Account> LinkedAccounts { get; set; }

Of course you can indent the dictionary to get better searching efficiency in case you have many linked accounts:

public Dictionnary<AccountClassificaiton, Dictionnary<Guid, Account>> LinkedAccounts { get; set; }

Or use a custom equality comparer treating Guid and AccountClassificaiton kind of a composite key: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.iequalitycomparer-1?view=net-5.0

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