简体   繁体   中英

Entity Framework creates a new column for each place I use a variable

I want to use Entity Framework 6.1 to store objects from classes with this layout:

Class Foo {
   int ID { get; set; }
   List<Bar> Names { get; set; };
   List<Bar> Addresses { get; set; };
   List<Bar> Nickname { get; set; };
}

Class Bar {
   int ID { get; set; }
   string Language  { get; set; }
  string value  { get; set; }
}

Entity Framework thanslates the Bar class into this columns in the table dbo.Bar in my database:

ID | Language | Bar_FooId1 | Bar_FooId2 | Bar_FooId3

I understand why it does so. It both needs a foreign key that maps the values in Bar to my Foo table, as well as a way to show which value in Foo it maps too.

This looks anything but good though, and the number of columns and cells quickly explodes, as I will be using Bar in quite a few objects in my Database.

Is it possible to do something else instead? Eg have a third table that links a row in Bar to a specific property by some identifier? Or maybe make a reference from the Foo table instead to the Bar row in question?

Thanks a lot!

Have you tried specifying the mapping?

protected override void OnModelCreating(
    DbModelBuilder modelBuilder)
{
    if (modelBuilder == null)
        throw new ArgumentNullException(nameof(modelBuilder));
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Foo>().HasMany<Bar>(_ => _.Names).WithRequired().Map(_ => _.ToTable("Names"));
    modelBuilder.Entity<Foo>().HasMany<Bar>(_ => _.Addresses).WithRequired().Map(_ => _.ToTable("Addresses"));
    modelBuilder.Entity<Foo>().HasMany<Bar>(_ => _.Nickname).WithRequired(_ => _.Foo).Map(_ => _.ToTable("NickNames"));
}

Incorrect, the above will not work!

I tried the above mappings, they will actually not not work, look here . You will at the very least have to create three separate classes with the same properties, Address , Nickname , and Name

That is not possible. EF cannot map same class twice within same context. Your single User class can be only mapped to Users table or TempUsers table in single context type. You need either two user classes or two different context types (with different mapping configuration) - one providing access to Users table and second providing access to TempUsers table.

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