简体   繁体   中英

How can I enforce a rule where only one instance of a class can have a certain parameter set to true?

In my.Net Core Entity Framework game, I have a relationship between the Castle and CastleKnights classes.

The Castle can have many CastleKnights associcated with one Castle.

But each Castle can only have one CastleKnight that is flagged as the imposter(IsImposter).

I'm trying to figure out how I can ensure that each Castle only has one CastleKnight that has the IsImposter flag set to true .

I tried this, putting this in my CastleKnights class, but it did not work:

if(IsImposter = true) {

}

It tells me that the name "IsImposter" does not exist in the current context .

How can I get the Casetle class to "know" when a Castle already has a CastleKnight with IsImposter set to true?

Thanks!

Here are my 2 classes:

 public partial class Castle
{
    public Castle()
    {
        CastleKnights = new HashSet<CastleKnights>();
    }
    [Key]
    public Guid CastleId { get; set; }
    public string CastleDescription { get; set; }

    public virtual ICollection<CastleKnights> CastleKnights { get; set; }
}


public partial class CastleKnights
{
    public Guid KnightId { get; set; }
    public Guid? CastleId { get; set; }
    public bool? IsImposter { get; set; }

    public virtual Castle Castle { get; set; }
}

You can achieve that placing a new readonly property on your Castle Class such as:

    public partial class Castle
    {
        ...

        public bool HasImposter
        {
            get
            {
                return CastleKnights.Where(knight => knight.IsImposter == true).SingleOrDefault() != null;
            }
        }
    }

And enforcing that whenever later in your code you create a new Knight instance, obliged yourself to provide some value for IsImpostor property

    public partial class CastleKnights
    {
        public CastleKnights(bool isImposter)
        {
            IsImposter = isImposter;
        }
        
        public bool IsImposter { get; private set; }
        ...
    }

Read more about Linq "Single" method here

Since you only ever need to track one imposter per castle, consider tracking them as a property in the Castle class:

 public partial class Castle
{
    public Castle()
    {
        CastleKnights = new HashSet<CastleKnights>();
    }
    [Key]
    public Guid CastleId { get; set; }
    public string CastleDescription { get; set; }
    public CastleKnights ImpostorKnight;

    public virtual ICollection<CastleKnights> CastleKnights { get; set; }
}

...then, just point to whichever instance of CastleKnights is the impostor.

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