Filter base entity from properties of child objects

I have been looking for a solution for several days.

I have eight objects in my application, a base and seven objects that inherit from this base object. Some child objects have the same properties.

public class LogEntry(){ public int LogEntryId{get;set;} public string ... } public class TestEntry : LogEntry{ .... public string SomeProperty{get;set;} //SomePropertyThatIsNotInBaseClass .... } public class XEntry : LogEntry{ .... public string SomeProperty{get; set;} .... } 

I am trying to filter the base object with this SomeProperty. I am trying to execute a query like

 var value = Db.LogEntry.Where(i=>i.SomePropery == "some string"); 

It is forbidden. I can only getwhat i want

 IQueryable<LogEntry> first = Db.LogEntry.OfType<TestEntry>.Where(i=>i.SomeProperty == "..."); IQueryable<LogEntry> second = Db.LogEntry.OfType<XEntry>.Where(i=>i.SomeProperty == "..."); ... 

And combine them at the end. Is there a smarter way to do than this method? Extension methods, etc.

Any help would be appreciated.

0
source share
1 answer

Edit

By carefully examining your example, I don’t think you are trying to do this. If you write a query by the type of the BASE object, you can only query fields that are defined in the base type.

Since "SomeProperty" is not defined in LogEntry, you cannot write this query:

 var logEntries = db.LogEntry.Where(r => r.SomeProperty == "foo"); 

Since SomeProperty is not defined in the LogEntry class.

If you want to write queries to the base class, you need to do something like the following:

 public class TPTContext : DbContext { public TPTContext() : base("name=TPT") { } public DbSet<BillingDetail> BillingDetails { get; set; } } public abstract class BillingDetail { public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; } } [Table("BankAccounts")] public class BankAccount : BillingDetail { public string BankName { get; set; } public string Swift { get; set; } } [Table("CreditCards")] public class CreditCard : BillingDetail { public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; } } 

I wrote the following query for the base class:

 TPTContext db = new TPTContext(); var allAccounts = db.BillingDetails.Where(b => b.Owner == "boran"); var bankAccounts = allAccounts.OfType<BankAccount>(); var creditCards = allAccounts.OfType<CreditCard>(); 

Everything seems to work well for me.

0
source

All Articles