如何在Entity Framework的另一个模型中使用模型?

时间:2013-09-05 12:39:06

标签: c#

这个想法是一个带有家具的房间。非常简单。这是Furni模型:

public class Furni
{
    public int ID { get; set; }
    public string Name { get; set; }
}
public class FurniDbContext : DbContext
{
    public DbSet<Furni> Furniture { get; set; }
}

当然,它工作正常。它耦合到一个像它应该的表。现在我正在写房间模型:

public class Room
{
    public int ID { get; set; }
    public Furni Furni { get; set; } <<<<< I have no idea how to couple it to FurniDbContext
}
public class RoomDbContext : DbContext
{
    public DbSet<Room> Rooms { get; set; }
}

有任何帮助吗? :)我希望我已经足够清楚了。

1 个答案:

答案 0 :(得分:0)

每个班级不需要单独的DbContext。它看起来像这样:

<强>间

public class Room
{
    public int ID { get; set; }
    public virtual Furni Furniture { get; set; } // virtual is for lazy loading
}

<强>家具

public class Furni
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual List<Room> Rooms { get; set; }  // if you want to have the relationship both ways
}

<强>的DbContext

public class AppDbContext : DbContext
{
    public DbSet<Furni> Furniture { get; set; }
    public DbSet<Room> Rooms { get; set; }
}

希望有所帮助。