简体   繁体   中英

C# .Net EF 6.1 Using object base class as property type does not map a db object

""I have Results object which I use to map a query used in multiple table:

public class Result
{
    public int Id{ get; set; }

    //Value could be bool, int, string, date
    public object Value { get; set; }
}

EF Calls

results.AddRange(context.Database.SqlQuery<Result>("SELECT Id, Value FROM ResultStrings")).ToList());
results.AddRange(context.Database.SqlQuery<Result>("SELECT Id, Value FROM ResultInt")).ToList());

The Id property gets populated but the Value remains null. Is there a way to populate Value property?

In a word, "don't"? :)

You are trying to pound a square EF entity through a hole of any possible shape. Declare Entities for each result table. They can share a common interface and expose an object "Value" if that is what you really want. Trying to cram them all into a single entity brings more problems, such as later resolving what table the record originally came from, and potential overlaps of IDs. Entity Framework is a mapper between objects and relational tables which is intended to be one to one so that operations can be related from table to object and back.

public abstract class Result
{
     public int Id { get; set; }
     public abstract object Value { get; }
}

public class IntResult : Result
{
     public int RawValue { get; set; }

     [NotMapped]
     public override object Value => return RawValue;
}

public class StringResult : Result
{
     public string RawValue { get; set; }

     [NotMapped]
     public object Value => return RawValue;
}

Then to query, unfortunately if you want "Value" to be the column name and the abstract common property name you need to alias the results. EF won't honour [Column("Value")] attributes when using SqlQuery .

results.AddRange(context.Database.SqlQuery<StringResult>("SELECT Id, Value AS RawValue FROM ResultStrings")).ToList());
results.AddRange(context.Database.SqlQuery<IntResult>("SELECT Id, Value AS RawValue FROM ResultInt")).ToList());

Alternatively, don't use EF to get these results. Just go to the database via ADO and query the data as you see fit to populate into a POCO Result object.

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