EF6对象关系

时间:2015-11-19 11:34:53

标签: c# entity-framework

我有一个数据库,我无法修改,因为它来自外部应用程序。数据库包含链接的表,但不包括键 - 外键结构。简化后,结构如下所示:

testreader = nltk.corpus.TaggedCorpusReader("filepath", r".*\.txt", encoding="Latin-1")

for line in testreader.raw(badfilename).splitlines():
    if re.search(r'[\x80-\xFF]', line)):
        print(line)

如您所见,这两个表可以通过WarehouseCode链接,但我不明白我在EF6中如何做到这一点。

1 个答案:

答案 0 :(得分:1)

编辑:第2卷。 看来你必须要等到EF7

• Support for specifying a foreign key associations that on the principal end specify columns(s) that comprise a unique constraint but are not the primary key,

似乎实体框架无法将一个仓库与一个仓位相关联,因为无法保证只有一个仓库具有该仓库代码。

参考 1 2

因此,解决方法可能是仅使用额外的表来建立多对多的关系。

public class Warehouse
{
    public Int32 Id { get; set; }
    public String WarehouseCode { get; set; }
    public String Description { get; set; }
    [InverseProperty("LocationWarehouses")]
    public virtual ICollection<Location> LocationsWithThisWarehouse{ get; set; }
}
public class Location
{
    public Int32 Id { get; set; }
    public String LocationCode { get; set; }
    public String Description { get; set; }
    public String WarehouseCode { get; set; }
    [InverseProperty("LocationsWithThisWarehouse")]
    public virtual Icollection<Warehouse> LocationWarehouses { get; set; }
}

public class YourContext: DbContext
{
    public DbSet<Location> Locations { get; set; }
    public DbSet<Warehouse> Warehouses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer < YourContext > (null);
        modelBuilder.Entity<Warehouse>().ToTable("Warehouse", "SchemaName");
        modelBuilder.Entity<Location>().ToTable("Location", "SchemaName");
        modelBuilder.Entity<Warehouse>().HasMany(g => g.LocationsWithThisWarehouse).WithMany(t => t.LocationWarehouses).Map(m =>
        {
            m.MapLeftKey("WarehouseCodeOnWarehouse");
            m.MapRightKey("WarehouseCodeOnLocation");
            m.ToTable("WarehouseAtLocation");
        });
    }
}