- Code First 如何设置字段为自增?
//两个方法
//’第一是使用DataAnotatation
public class Sale
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
//第二个方法,使用Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Sale>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
查看DatabaseGeneratedOption,可以看到是一个enum,定义如下:
public enum DatabaseGeneratedOption
{
None = 0,
Identity = 1,
Computed = 2,
}
熟悉SQL Server的应该知道,另外一个Computed对应SQL Server中的计算字段。计算字段稍微复杂些,此处不详述。更多有关Data Anotation请参阅官方文档 MSDN Entity Framework Code First Data Annotations。
- SQL LocalDB的连接字符串如何设置?
<pre>
SQL Server 2012 LocalDB, 使用:
<connectionStrings><add name="SchoolContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ContosoUniversityDB.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" /></connectionStrings>
------------------- 我是分隔线 --------------------
SQL Server 2014 LocalDB:
<connectionStrings><add name="SchoolContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ContosoUniversityDB.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" /></connectionStrings>
</pre>Data Source 从 ** (LocalDB)\v11.0 ** 修改为** (LocalDB)\MSSQLLocalDB **。
注意其中的|DataDirectory| - |DataDirectory|在哪儿?
For applications that are put in a folder on the user's computer, the database folder uses the application folder.
对于部署在用户计算机某个文件夹的应用程序,DataDirectory就是应用程序文件夹。
For applications that are running under ClickOnce, the database folder uses the specific data folder that is created.
对于部署在用户计算机某个文件夹的应用程序,DataDirectory就是应用程序文件夹。
For Web apps, this will be the App_Data folder
对于Web应用,DataDirectory = ** “App_Data” **文件夹
也可以通过代码修改
AppDomain.CurrentDomain.SetData(“DataDirectory”, newpath)
- 新问题