0
我建設上的Visual Studio 2012年實體框架不工作作爲SaveChanges()
桌面基礎的應用發生它沒有給出一個例外,似乎數據已經輸入,但刷新後數據庫中沒有添加額外的行。實體框架是不是在N層架構的工作
對於演示中,我提出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>
我App.Config中在DAL是....
<?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>
所以,我怎麼能得到修改數據庫'調試folder'存在於瀏覽以及在DAL ... – ButtGenius
非常感謝'Erik' ......你讓我的日子。).......我更改了| DataDirectory |與數據庫的絕對路徑和它按預期完美工作 – ButtGenius