简体   繁体   English

实体框架为我使用变量的每个位置创建一个新列

[英]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: 我想使用Entity Framework 6.1存储具有以下布局的类中的对象:

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: 实体框架将Bar类分解为数据库中表dbo.Bar的以下列:

ID | ID | Language | 语言| Bar_FooId1 | Bar_FooId1 | Bar_FooId2 | Bar_FooId2 | Bar_FooId3 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. 它既需要将Bar中的值映射到我的Foo表的外键,也需要显示它也映射了Foo中的哪个值的方法。

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. 但是,这看起来并不好,而且列和单元格的数量迅速激增,因为我将在数据库中的许多对象中使用Bar。

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? 例如,有第三个表通过某些标识符将Bar中的行链接到特定属性? Or maybe make a reference from the Foo table instead to the Bar row in question? 还是可以从Foo表中引用相关的Bar行?

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 您至少必须创建三个具有相同属性的单独的类,即AddressNicknameName

That is not possible. 这是不可能的。 EF cannot map same class twice within same context. EF无法在同一上下文中两次映射同一类。 Your single User class can be only mapped to Users table or TempUsers table in single context type. 您的单个User类只能以单个上下文类型映射到Users表或TempUsers表。 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. 您需要两个用户类或两个不同的上下文类型(具有不同的映射配置)-一种提供对Users表的访问,另一种提供对TempUsers表的访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM