2015-04-30 16 views
0

我正在尝试使用EF7我已经在config.json和Startup.cs中配置了所有设置,添加条件时 - “已配置关系存储,但未指定要使用的DbConnection或连接字符串。”

能够添加和应用迁移。 1-同时改变它不会对数据库应用的字段长度,代码看起来像

[StringLength(100)] 
public int Text { get; set; } 

2 - 当我写在那里的条件比实体收到此错误“关系存储已经配置而不指定的的DbConnection或连接字符串使用” 我的代码看起来像

TestContext db = new TestContext(); 
var cust = db.Customers.Where(x => x.id == text).FirstOrDefault(); 

我究竟做错了什么?

Config.json

{ 
    "Data": { 
     "DefaultConnection": { 
      "ConnectionString": "Server=Jay-PC;Database=TestDb;User Id=sa; Password=xxx;MultipleActiveResultSets=true" 
     } 
    }, 
    "EntityFramework": { 
     "TestContext": { 
      "ConnectionString": "Data:DefaultConnection:ConnectionString" 
     } 
    } 
} 

Startup.cs

public class Startup 
    { 
     public Startup(IHostingEnvironment env) 
     { 
      Configuration = new Configuration() 
       .AddJsonFile("config.json") 
       .AddEnvironmentVariables(); 
     } 

     public IConfiguration Configuration { get; set; } 

     public void ConfigureServices(IServiceCollection services) 
     { 
      services.AddEntityFramework(Configuration) 
       .AddSqlServer() 
       .AddDbContext<TestContext>(); 
      services.AddMvc(); 

     } 
} 

我的上下文看起来像

public class TestContext : DbContext 
    { 
     public DbSet<Contact> Contacts { get; set; } 
     public DbSet<Customer> Customers { get; set; } 

     public TestContext() 
     { 
     } 
     protected override void OnConfiguring(DbContextOptions options) 
     { 
      options.UseSqlServer(); 
     } 

     protected override void OnModelCreating(ModelBuilder modelBuilder) 
     { 
      base.OnModelCreating(modelBuilder); 
     } 
    } 

任何帮助..

+0

你能分享你'config.json',而且你要Startup.cs'请 –

+0

@aguafrommars我已经更新了我的问题。 – jkyadav

+0

你能分享你的'DbContext'类吗?如果它具有由新项目模板添加的可怕构造函数,则在使用迁移之前需要将其删除。 – bricelam

回答

0

你需要告诉代码是连接字符串使用,没有选择默认的魔法逻辑。

这里是如何做到这一点的例子:https://github.com/aspnet/MusicStore/blob/master/src/MusicStore/Startup.cs#L43-L46

+0

我已经尝试了上面的解决方案,不幸的是它不工作,如果我们需要在Startup.cs文件中手动指定,那么为什么我们需要写这些行“EntityFramework”:{“TestContext”:{“ConnectionString”:“Data:DefaultConnection :ConnectionString“}在config.json中?这些线的用途是什么? – jkyadav

相关问题