C
C#•12mo ago
UltraWelfare

Simplifying creation of inherited classes

class Entity {
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public int? FieldA { get; set; }
public int? FieldB { get; set; }

}

class Base {
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
}

class A : Base {
public int FieldA { get; set; }
}

class B : Base {
public int FieldB { get; set; }
}
class Entity {
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public int? FieldA { get; set; }
public int? FieldB { get; set; }

}

class Base {
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
}

class A : Base {
public int FieldA { get; set; }
}

class B : Base {
public int FieldB { get; set; }
}
Entity entity = GetEntityFromDatabase();
if (entity.Field1 == "A") {
return new A {
Field1 = entity.Field1,
Field2 = entity.Field2,
Field3 = entity.Field3,
FieldA = entity.FieldA.Value
};
} else if (entity.Field2 == "B") {
return new B {
Field1 = entity.Field1,
Field2 = entity.Field2,
Field3 = entity.Field3,
FieldB = entity.FieldB.Value
};
}
Entity entity = GetEntityFromDatabase();
if (entity.Field1 == "A") {
return new A {
Field1 = entity.Field1,
Field2 = entity.Field2,
Field3 = entity.Field3,
FieldA = entity.FieldA.Value
};
} else if (entity.Field2 == "B") {
return new B {
Field1 = entity.Field1,
Field2 = entity.Field2,
Field3 = entity.Field3,
FieldB = entity.FieldB.Value
};
}
Basically we need to fetch Entity from the database and then map it into A or B depending on a field. That means you'll have to repeat the field copies a lot. With more fields and more "A"-"B"-"C"-"D"s... this will become a nightmare to maintain. Any other ideas?
2 Replies
UltraWelfare
UltraWelfareOP•12mo ago
I guess the only solution is to use an automatic mapper or just copy the fields over and over again 🥲
Anu6is
Anu6is•12mo ago
Are you using an ORM? EF Core should be able to handle this with discriminators
Want results from more Discord servers?
Add your server