开发者

single entity for different tables

I have same type of tables

ProductCodeTable, CountrycodeTable etc

All have key, value as their fields

When I use entity frame work, Can I have a single entity for all these tabl开发者_C百科es such that I can formulate different queries to get data from different tables?


You can create a base class for all of them and create sub class for each entity

public abstract class LookUpEntity
{
    [Key]
    public int Key { get; set; }

    [Required]
    public string Value { get; set; }
}

[Table("ProductCodeTable")]
public class ProductCode : LookUpEntity
{

}

This way you can model the relationships also and later if you wanted to add specific properties to those look up entities with out affecting other entities.


You can create a view with a Union of all tables like this:

create view AllKeyTables as 

SELECT 'Product' as table, Productkey as Key, nameProduct as name 
FROM ProductCodeTable
UNION
SELECT 'Country' as table, CountryISO as key, CountryName as name 
FROM CountrycodeTable
UNION
...

Then update EF model and check 'table' and 'key' fields as Entity Primary Key.

Next question you will do is: 'How can I make a relation between this Entity and existing Entities?' The answer is 'you can't because EF is not able to join Entities between other fields than primary key'. Then, before implement this solution, be sure that this is you are looking for.


EF supports this only if you model it as inheritance (@Eranga showed it in code-first approach). You will have single base entity and derived entity for each table so you will not avoid having different type for each table. Otherwise the answer is no.

Inheritance will put additional requirements on data in your tables. For example Ids will have to be unique among all tables. So if ProductTableCode will have record with Id 1, CountryCodeTable (and any other code table) mustn't have record with Id 1.

Also inheritance in EF can produce nasty and very poorly performing queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜