0

There are two entities A and B. They have a one to many relationship. Assume A to be the following type.

class A
{
        public int Id { get; set; }
        public bool isActive{ get; set; }
        public ICollection<B> BCollection{ get; set; }
        //Rest Of A properties
}

class B
{
        public int Id { get; set; }
        public A A{ get; set; }
        public int AId{ get; set; }
        public bool isAActive{ get; set; }
        //Rest of B Properties
}

S in B AId is foreign key of the primary key Id in A. This entity framework configured by itself due to having an A instance in B.

Is there a way via entity framework that I can configure my DBSet so that value of isAActive is automatically set depending on value of isActive in A?

Nemesis
  • 135
  • 1
  • 1
  • 13
  • I don't there there is a way to set it from fluent api or attribute binding like what you want but you may want to check out object mapper like Automapper to help you. this link might interest you abit. "https://stackoverflow.com/questions/6872610/automapper-one-to-many-relation". it use eager loading to update the id. you can replace with isAActive. – phonemyatt Dec 02 '19 at 03:58
  • I think your entities should map as close as possible to the database schema, otherwise you're representing denormalization. What you're trying to describe looks like a "domain model", which is supposed to represent a better version of the system or business domain [since the database / entity model is bound by database design principles]. – thinkOfaNumber Dec 02 '19 at 05:00
  • In my opinion `B.IsAActive` is just the same value of `B.A.isActive`,you could just get `IsAActive` from the navigation property. – Ryan Dec 04 '19 at 02:47

1 Answers1

1

not sure if this is the kind of thing you are looking for but using a constructor might be helpful

public  class A
{
    public int id { get; set; }
    public bool isActive { get; set; }
    public List<B> BCollection { get; set; }
}

public class B
{
    public B (A a){
        isAActive = a.isActive;
        }
    public int id { get; set; }
    public A A { get; set; }
    public bool isAActive { get; set; }
}

static void Main(string[] args)
{
    A a = new A()
    {
        id = 1,
        isActive = true
    };
    A a2 = new A()
    {
        id = 2,
        isActive = false
    };

    List<B> bs = new List<B>()
    {
        new B(a) { id = 100, A = a},
        new B(a) { id = 200, A = a}
    };
    a.BCollection = bs;

    List<B> bs2 = new List<B>()
    {
        new B(a2) { id = 300, A = a2},
        new B(a2) { id = 300, A = a2}
    };
    a2.BCollection = bs2;

    return;
}

a.BCollection will have the isAActive set to true
a2.BCollection will have the isAActive set to false

Jawad
  • 11,028
  • 3
  • 24
  • 37