EF6:将具有复杂类型的实体映射到一个表

时间:2014-06-03 15:01:06

标签: entity-framework

我有一个具有复杂类型的实体,我使用CodeFirst就像这样:

public class Session
{
    public int SessionId { get; set; }

    public DateTime CreationDate { get; set; }

    public Folder SessionFolder { get { set; } 

}

public class Folder
{
    string _path;

    public Folder(string path)
    {
        _path = path;
    }

    public string Path
    {
        get { return _path; }
    }
}

我正在使用Fluent API而我只想制作一个表,这个结构的会话表:

SessionId as int
CreationDate as datetime
Path as nvarchar(255)

我该怎么办?

1 个答案:

答案 0 :(得分:1)

在Entity Framework 6中,您可以通过DbContext指定保存实体的表:

public class YourContext : DbContext
{
    public YourContext() : base("YourContext")
    {
    }

    public DbSet<Session> Sessions{ get; set; }
    public DbSet<Folder> Folders{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Saves the Session and folder in the same table, but allows for individual fetches
        modelBuilder.Entity<Session>().HasRequired(s => s.Folder).WithRequiredPrincipal();
        modelBuilder.Entity<Session>().ToTable("SessionFolderTable");
        modelBuilder.Entity<Folder>().ToTable("SessionFolderTable");
    }
}