C# 实体框架的默认SQL Server

C# 实体框架的默认SQL Server,c#,sql-server,entity-framework,C#,Sql Server,Entity Framework,我有两个SQL Server实例-SQLEXPRESS和MSSQLServer 2017。我的实体框架测试应用程序在SQLEXPRESS中创建数据库。在哪里定义了SQL Server实体框架应使用的实例 测试应用: public class Person { public int Id { get; set; } public string Name { get; set; } } public class PeopleConte

我有两个SQL Server实例-
SQLEXPRESS
MSSQLServer 2017
。我的实体框架测试应用程序在
SQLEXPRESS
中创建数据库。在哪里定义了SQL Server实体框架应使用的实例

测试应用:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class PeopleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }

    static void Main(string[] args) // using DB
    {
        try
        {
            using (PeopleContext ctx = new PeopleContext())
            {
                ctx.People.Add(new Person() { Id = 1, Name = "John Doe" });
                ctx.SaveChanges();
            }

            using (PeopleContext ctx = new PeopleContext())
            {
                Person person = ctx.People.SingleOrDefault(p => p.Id == 1);
                Console.WriteLine(person.Name);
            }

        }
        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        Console.WriteLine("finish");
        Console.ReadLine();
    }
EF如何决定使用哪一个?

您可以使用:

public class PeopleContext : DbContext
{
    public PeopleContext() : base("Database") //it makes reference to the connection string defined in the app.config
    {     
    }
    public IDbSet<Person> People { get; set; }
}
公共类PeopleContext:DbContext
{
public PeopleContext():base(“Database”)//它引用app.config中定义的连接字符串
{     
}
公共IDbSet人员{get;set;}
}
在app.config中:

<connectionStrings>
<add name="Database" connectionString="Data Source=source;Initial Catalog=Your_database;Integrated Security=True" providerName="System.Data.SqlClient" />


要查找
服务器
用户名
密码
默认数据库
,您应该查找实体框架正在使用的连接字符串。

您不指定使用哪个版本的实体框架,但是大多数版本将连接字符串存储在
web.config
app.config

或者,您可以通过Visual Studio的调试模式进入
PeopleContext
构造函数以查看连接字符串,或者在.Net Core中,通过
PeopleContext.cs
中的
OnConfigure
方法可以找到连接字符串


否则,您可以在整个解决方案中搜索
Ctrl+f

我有几个连接字符串。EF如何决定使用哪一个?UPD中的更多详细信息。@Vico:如果它选择了带有非具体DbContext的SQL Express,则可能会选择SQL Express作为默认值。MSDN,“如果不指定连接字符串,Entity Framework将在users目录中创建一个具有DbContext类的完全限定名的LocalDB数据库”。请参见结尾。@HugoUchoBruno Nevermind,用户已删除该评论。
<connectionStrings>
<add name="Database" connectionString="Data Source=source;Initial Catalog=Your_database;Integrated Security=True" providerName="System.Data.SqlClient" />