我正在visual studio 2012上构建一个基于桌面的应用程序。实体框架无法正常工作SaveChanges()
出现它不会出现异常,似乎已输入数据但刷新数据库后没有添加额外的行在它。
对于演示,我制作了2层架构。
我的观点是......
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyDAL dal = new MyDAL();
if (dal.Add(StudentName.Text, Contact.Text))
{
MessageBox.Show("Addition Successfull");
}
else
{
MessageBox.Show("Addition Failed");
}
}
}
我的数据访问层........
public class MyDAL
{
public bool Add(string name, string contact)
{
using (var db = new Database1Entities())
{
Student s = new Student();
s.StudentName = name;
s.ContactNo = contact;
try
{
db.Students.Add(s);
db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
我的数据库脚本是.....
CREATE TABLE [dbo].[Student] (
[Student_Id] INT IDENTITY (1, 1) NOT NULL,
[StudentName] VARCHAR (50) NULL,
[ContactNo] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Student_Id] ASC)
);
我的App.Config in View
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
我在DAL的App.Config是......
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
答案 0 :(得分:1)
它按预期工作。这是对|DataDirectory|
选项的简单误解。
编译解决方案时,数据库正被复制到\Debug\|DataDirectory|
,并且文件正在被修改。
您很可能正在查看解决方案(visual studio)中的文件,该文件 not 正被Debug
目录中的可执行文件修改。