使用实体连接到现有表

时间:2015-12-01 19:44:16

标签: c# asp.net-mvc entity-framework datacontext

我有一个解决方案,我已经创建了一段时间,我使用EF Code First迁移来创建数据库。最近另一个解决方案我的主管在数据库上运行了一些添加了几个表的脚本。现在,我需要在我的解决方案中连接到这些表。我在这里有这个代码:

public class RoleMap : EntityTypeConfiguration<Role>
{
    public RoleMap()
    {
        //Primary key
        this.HasKey(t => t.RoleId);

        this.Property(t => t.ApplicationId)
            .IsRequired();

        this.Property(t => t.Description)
            .HasMaxLength(256);

        this.Property(t => t.RoleName)
            .IsRequired()
            .HasMaxLength(256);

        this.Property(t => t.LoweredRoleName)
            .IsRequired()
            .HasMaxLength(256);


        this.ToTable("aspnet_Roles");
        this.Property(t => t.RoleId).HasColumnName("RoleId");

        this.Property(t => t.ApplicationId).HasColumnName("ApplicationId");
        this.Property(t => t.Description).HasColumnName("Description");
        this.Property(t => t.LoweredRoleName).HasColumnName("LoweredRoleName");
        this.Property(t => t.RoleName).HasColumnName("RoleName");

    }
}

static DataContext()
{
       Database.SetInitializer<DataContext>(null);
}

public DataContext(): base("DefaultConnection")
{
}


public DbSet<Role> Roles { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Configurations.Add(new RoleMap());

}

我在此链接中找到了此代码:

http://www.codeproject.com/Tips/661053/Entity-Framework-Code-First-Map

不幸的是,当我尝试创建一个新的迁移时 - 它正在尝试创建一个新表(即使我告诉它表已经存在)。

public partial class addRoles : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                 "dbo.aspnet_Roles",
                 c => new
                    {
                        RoleId = c.Guid(nullable: false),
                        ApplicationId = c.Guid(nullable: false),
                        Description = c.String(maxLength: 256),
                        LoweredRoleName = c.String(nullable: false, maxLength: 256),
                        RoleName = c.String(nullable: false, maxLength: 256),
                    })
                .PrimaryKey(t => t.RoleId);

       }

       public override void Down()
       {
            DropTable("dbo.aspnet_Roles");
       }
  }

1 个答案:

答案 0 :(得分:0)

在JamieD77的帮助下,我找到了解决方案。它是此链接中的代码优先映射的组合:

Code First Mapping

然后在这里添加-ignorechanges add-migration

Code First Migrations With Existing Table