简体   繁体   中英

Can Entity Framework 6 map foreign keys from a delimited string column?

I am trying to read from a database which unfortunately has be designed to store foreign keys in a delimited string rather than a separate table, and I don't have the option to change the database structure. As an example:

Table 1 - Person

ID Name Fruit
1 "Bob" "1;3;5"
2 "Dave" "2;4;6"
3 "Mary" "1;2;3"
4 "Jane" "4;5;6"

Table 2 - Fruit

ID Name
1 "apple"
2 "banana"
3 "orange"
4 "pear"
5 "lemon"
6 "lime"

Each number within the [Person.Fruit] column string maps to a [Fruit.ID] record, and I would like to be able to access the equivalent of a List<Fruit> on my Person class through EF.

Is it possible to configure entity framework (specifically 6, maybe in the OnModelCreating method) to use the split and parsed ids in this column as foreign keys in memory? I don't intend to change the database, I just want to read from it easily with linq, but without access to the other table when it is constructed I can't do it manually within the class.

I am aware that EF Core has a value conversion mechanism, but I haven't been able to find an example where it converts from a single value to a foreign key based list navigation property. The reason I'm not using Core is because I am already using EF6 in the same project to access another database, and I'm not sure if I can use both in the same process.

I suppose it might be possible to build the extra many<->many mapping table when first accessing the database, as long as it doesn't change the structure of the other tables as they are being used by another black-box library.

I'm open to any suggestions of how I can either use EF6 with or without modifying the database, or EF Core, as long as it's possible to avoid issues with the existing EF6 implementation, it doesn't break the existing database structure and I can do it all from C#.

In case it helps, the database is SQLite, which has already been some fun to get working at all.

Cheers.

You could add a partial class to your project for this table, that includes a property

public partial class Person
{
     public List<int> FruitIds => this.Fruit.Split(';').Select(int.Parse).ToList();
}

But you can only use that in materialized data in code, not in database statements to automatically include or select things.

If you cannot change a database that is broken, then there is little you can do about it.

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