我正在 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 在视图中
<?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>