简体   繁体   中英

Using Generics with EF classes

I'm using EF6 with Code First and have a few tables with virtually the same schema. I would like to be able to perform queries on these tables and return the results to a common object (class) rather than creating a new one for each.

So for example, EF won't allow:

public class Product1 {
    public int id { get; set; }
    public string name { get; set; }
}

public DbSet<Product1> Products1 { get; set; }
public DbSet<Product1> Products2 { get; set; }

So I have to define a second POCO:

public class Product1 {
    public int id { get; set; }
    public string name { get; set; }
}

public class Product2 {
    public int id { get; set; }
    public string name { get; set; }
}

public DbSet<Product1> Products1 { get; set; }
public DbSet<Product2> Products2 { get; set; }

At least I would like to be able to treat results from these POCOs the same so that I can plug results into another class:

public class SomeClass {
    public <Product1 or Product2> Product { get; set; }
}

Be able to store the result from either db table in the same object:

SomeClass someclass = new SomeClass();

someclass.Product = _context.Products1.Where(p => p.id == 1).First();

or

someclass.Product = _context.Products2.Where(p => p.id == 1).First();


int thisId = someclass.Product.id;

How do I make someclass.Product generic so that it will accept either Product1 or Product2?

You would have to make the classes inherit from an interface and then use that interface in a generic type constraint.

public interface IProduct 
{
    int id { get; set; }
    string name { get; set; }
}

public class Product1 : IProduct
{
    public int id { get; set; }
    public string name { get; set; }
}

public class Product2 : IProduct
{
    public int id { get; set; }
    public string name { get; set; }
}

Then you could define SomeClass as follows:

public class SomeClass<TProduct> where TProduct : IProduct 
{
    public TProduct Product { get; set; }
}

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