有,我有有由FK有关的几个“层”目标表的情况下。
Root
|__A
|__B
|__C
|__D
我从平面文件导入一些数据,结果伸入一组非常相似的POCO对象。从那里,我需要从这些POCO对象,并进入实体选择。现在的问题是如何最好地处理更新因为每个级别可以是新的或已经存在和需要更新的实体。
例如,根对象本身可能已经被创建,但不包含A,因此,一个必须被创建,然后它的依赖对象添加。
类似的,根可能已经存在,以及A,但不依赖于它的B.每个层次都有需要更新的具体领域,如果他们已经存在。
我认为有一个在您层的一个一对多的关系:每根都有零个或多个作为,每次都只属于一个根,使用外键。每次都有零个或多个B类,每一个B属于只有一个A,使用外键等。
在实体框架,你会碰到这样的:
class Root
{
public int Id {get; set;}
... // other properties
// every Root has zero or more As (one-to-many):
public virtual ICollection<A> As {get; set;}
}
class A
{
public int Id {get; set;}
... // other properties
// every A belongs to exactly one Root, using foreign key
public int RootId {get; set;}
public virtual Root Root {get; set;}
// every A has zero or more Bs:
public virtual ICollection<B> Bs {get; set;}
}
class B
{
public int Id {get; set;}
... // other properties
// every B belongs to exactly one A, using foreign key
public int AId {get; set;}
public virtual A A {get; set;}
// every B has zero or more Cs:
public virtual ICollection<C> Cs {get; set;}
}
etc.
在实体框架表格的列由非虚拟性表示。虚拟属性表示各表之间的关系(一到很多很多一对多)
你提到它可以是您已经阅读您的文件目录root1和别的孩子再读一个目录root1。看来你的文件是平的:
Root1, A1, B1, ...
Root1, A1, B2, ...
Root1, A2, B3, ...
Root2, A3, B4, ...
Root1, A4, B5, ...
显然,你有一个函数来读取一个文件的“线”:
class Line
{
public Root Root {get; set;}
public A A {get; set;}
public B B {get; set;}
...
}
IEnumerable<Line> ReadLines(...) {...}
void FillDatabase(IEnumerable<Line> lines)
{
// convert the lines into a sequence or Roots with their As,
// with their Bs, with their Cs, ...
IEnumerable<Root> roots = lines.GroupBy(line => line.Root,
(root, linesOfThisRoot) => new Root
{
Name = root.Name,
... other root properties
As = linesOfThisRoot.GroupBy(line => line.A,
(a, linesWithRootAndA) => new A
{
Name = a.Name,
... other a properties
Bs = linesWithRootAndA.GroupBy(line => line.B,
(b, linesWithRootAB) => new B
{
... B properties
Cs = linesWithRootAB.GroupBy(line => line.C,
{
etc.
})
.ToList(),
})
.ToList(),
})
.ToList(),
})
.ToList();
});
using (var dbContext = new MyDbContext()
{
dbContext.Roots.AddRange(roots.ToList());
dbContext.SaveChanges();
}
}