如何在asp mvc中使用一个数据库

时间:2015-03-17 08:54:17

标签: asp.net-mvc entity-framework dbcontext

public class project
{
    public int id { get; set; }
    public string ProjectName { get; set; }
    public string Description { get; set; }
    public string Category { get; set; }
    public int UserprojectId { get; set;  }
    public int? SponserId { get; set; }
    public decimal Cost { get; set; }
    public DateTime CreatedTime { get; set; }
    public DateTime EstimateTime { get; set; }

}
public class projectDB : DbContext
{
    public DbSet<project> projects { get; set; }
}

和这个模型

public class sponser
{
    public int id { get; set; }
    public string FirstName { get; set; }
    public string lastName { get; set; }
    public string CompanyName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }

    public DateTime DateRegister { get; set; }
    public String CompanyPhone { get; set; }
    public string CellPhone { get; set; }
    public string Email { get; set;  }
    public bool EmailConfirmation { get; set; }
    public string Country { get; set; } 
    public string City { get; set; }
    public string PostalCode { get; set; }
    public String Address { get; set; }

}
public class sponserDB : DbContext
{
    public DbSet<sponser> sponsers { get; set; }
}

并在我的网站配置文件中 我添加此名称

<add name="SponseringDB"
  connectionString="Data Source=(localdb)\v11.0;Initial Catalog=sponseringDB;Integrated Security=True"
  providerName="System.Data.SqlServerCe.4.0"
/>

当运行它并为我创建一些Record时,它首先创建了两个数据库sponseringDb,第二个是projectDb我想使用一个数据库。

需要有关实现这一目标的建议。

1 个答案:

答案 0 :(得分:2)

你有两个DbContext继承的类,这就是创建2个数据库的原因,如果你想只有一个数据库,即:projectDB

将projectDB类更改为

    public class projectDB : DbContext
    {

   public projectDB () : base("projectDBConnectionString") //<- name of your connection string
        {
        }
        public DbSet<project> projects { get; set; }
        public DbSet<sponser> sponsers { get; set; }
    }

并在您的Web配置中添加名为'projectDBConnectionString'的连接字符串,即:

<add name="projectDBConnectionString"
  connectionString="Data Source=(localdb)\v11.0;Initial Catalog=sponseringDB;Integrated Security=True"
  providerName="System.Data.SqlServerCe.4.0"
/>

现在您可以从web.config中删除连接字符串'SponseringDB'并删除类'sponserDB'

希望有所帮助