Click here to Skip to main content
15,889,879 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a model (let's call it "foo") that can have multiple children of another model (let's call that one "bar"). Now I would like for foo to have both a collection of child bar models, but I also would like for foo to have a variable of type "bar" that is only populated by the one bar child with "IsActive" set to true. Is this possible with fluent or annotations?

Here is what the classes would sort of look like (not exactly, just enough to get the idea across):

class foo
{
int FooID;
Bar ActiveBar;
ICollection<bar> Bars;
}

class bar
{
int BarID;
int FooID;
bool IsActive;
}

What I have tried:

I looked into the fluent for establishing foreign keys and principal keys, but this is more of a "where" situation.I am now sure where to look for achieving this relationship...if it is even possible.
Posted
Updated 5-Aug-21 1:45am

how about

C#
class foo
{
  public Bar ActiveBar { get; private set; }
  public IReadonlyCollection<bar> Bars { get; }

  public void SelectBarAt(int index); // <<== magic happens here
}
 
Share this answer
 
Comments
TimWallace 5-Aug-21 6:26am    
Thanks Lloyd, but I was hoping for a way to create a "pure" model - properties only - using Entity Framework Core Code first
Assuming you don't actually need that relationship embedded in the database, you can simply do:
C#
class Foo
{
    public ICollection<Bar> Bars { get; set; }
    public Bar ActiveBar => Bars?.FirstOrDefault(b => b.IsActive);
}
You'll probably also want a unique filtered index on the Bar table, so that you can only have one active Bar per Foo:
C#
modelBuilder.Entity<Bar>().HasIndex(b => b.FooID).IsUnique().HasFilter("IsActive = 1");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900