简体   繁体   English

实体框架无法保存在数据库中

[英]Entity Framework Can't Save in Database

I've got a problem with the entity framework as it's my first time using it along with SQL server. 我在实体框架上遇到了问题,因为这是我第一次与SQL Server一起使用它。 I managed to successfully create an entity data model with an entity called EMP. 我设法通过名为EMP的实体成功创建了一个实体数据模型。 EMP has ID, Name, and Salary as scalar properties. EMP具有ID,Name和Salary作为标量属性。 I then generated the database from the model, copy/pasted the resulting sddl into SQL server and created my database. 然后,我从模型生成数据库,将生成的sddl复制/粘贴到SQL Server中,并创建了数据库。 I went back into VS 2010 express and tried adding some records into the database using the following code: 我回到VS 2010 Express,并尝试使用以下代码将一些记录添加到数据库中:

string constr = ConfigurationManager.ConnectionStrings["dataemp"].ConnectionString;
dataemp db = new dataemp(constr);

db.AddToEmps(Emp.CreateEmp(0, "john", "Informatique", "10000000 cfa"));
db.AddToEmps(Emp.CreateEmp(1, "johny greg", "finances", "100000000 cfa"));

db.SaveChanges();//i get the error here
Console.WriteLine(
  "*********Employee actuellement dans la database*********\n{0}",
  query.ToString());

As a result the compiler gives me an exception as if I didn't connect to the database or as if it couldn't access the database but it is displayed in the database explorer. 结果,编译器给了我一个异常,好像我没有连接到数据库,或者好像它无法访问数据库,但是它显示在数据库浏览器中。 One more point in the database explorer: I can't see the tables(EMPs) whereas in SQL Server I am able to see it as dbo.Emps. 数据库浏览器中的另一点:我看不到表(EMP),而在SQL Server中,我可以将其视为dbo.Emps。 Here is the exception the compiler shows me: 这是编译器向我显示的异常:

Unhandled Exception: System.Data.UpdateException: An error occurred while updating the entries. 未处理的异常:System.Data.UpdateException:更新条目时发生错误。 See the inner ex ception for details. 有关详细信息,请参见内部说明。 ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Emps'. ---> System.Data.SqlClient.SqlException:无效的对象名称'dbo.Emps'。
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStre am, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String res etOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Bo olean returnStream, String method, DbAsyncResult result) 在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()处System.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,布尔breakConnection)在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection) .SqlClient.TdsParser.Run(位于System.Data.SqlClient.SqlDataReader.get处的System.Data.SqlClient.SqlDataReader.ConsumeMetaData()中的。 System.Data.SqlClient.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,String res etOptionsString)在System.Data.SqlClientSql处位于System.Data.SqlClientSql中。 RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔型returnStream,String方法,DbAsyncResult结果) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Bo olean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Bolean returnStream,String方法)在System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior行为,String方法)在System.Data.SqlClient.SqlCommand。 ExecuteDbDataReader(CommandBehavior行为),位于System.Data.Common.DbCommand.ExecuteReader(CommandBehavior行为)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnec tion connection, Dictionary 2 identifierValues, List 1 generatedValues) at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapt er adapter) --- End of inner exception stack trace --- at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapt er adapter) at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) 在System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager,IEntityAdapter)处System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator转换器,EntityConnection连接,词典2 identifierValues, List 1个GeneratedValues)适配器)-内部异常堆栈跟踪的结尾--在System.Data.EntityClient.EntityAdapter.Update(IEntityStateManagerEntityCache)处的System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager,IEntityAdapter Adapter)在System.Data.Objects.ObjectContext.SaveChanges(SaveOptions选项)
at ConsoleApplication1.Program.Main(String[] args) in D:\\Users\\ITA Final\\documents\\visual studio 2010\\Project s\\zut\\zut\\Program.cs:line 13 在D:\\ Users \\ ITA Final \\ documents \\ visual studio 2010 \\ Project s \\ zut \\ zut \\ Program.cs:line 13的ConsoleApplication1.Program.Main(String [] args)中

I have read many tutorials on entity framework and linq to entities. 我已经阅读了很多有关实体框架和linq到实体的教程。 I can't figure out what I am doing wrong here. 我无法弄清楚我在做什么错。

The only way for this error to occur, is for the table to not exist in the database you're connecting to. 发生此错误的唯一方法是使表不存在于您要连接的数据库中。 The connection string you're using for the context cannot be correct. 您用于上下文的连接字符串不正确。 This could occur if the value of the connection string in the Web or App config files is wrong, or you're setting that connection string by hand and setting it wrong. 如果WebApp配置文件中的连接字符串的值错误, 或者您手动设置该连接字符串并将其设置为错误,则可能会发生这种情况。

Given that you are having a problem with something not existing in a database, which indicates bad connection, and given your connection string, 假设您遇到的问题是数据库中不存在的问题(表示连接错误),并且给出了连接字符串,

connectionString="metadata=res:// /Model1.csdl|res:// /Model1.ssdl|res://*/Model‌​1.msl;provider=System.Data.SqlClient;provider connection string='Data Source=.\\SQLEXPRESS;AttachDbFilename="D:\\Users\\ITA Final\\Documents\\Visual Studio 2010\\Projects\\employee.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True'" connectionString =“ metadata = res:// /Model1.csdl|res:// /Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider连接字符串='数据源=。\\ SQLEXPRESS; AttachDbFilename =“ D:\\ Users \\ ITA Final \\ Documents \\ Visual Studio 2010 \\ Projects \\ employee.mdf”;集成安全性= True;连接超时= 30;用户实例= True; MultipleActiveResultSets = True'“

where the actual connection string used by ADO is ADO使用的实际连接字符串在哪里

Data Source=.\SQLEXPRESS;
AttachDbFilename="D:\Users\ITAFinal\Documents\Visual Studio 
    2010\Projects\employee.mdf";
Integrated Security=True;
Connect Timeout=30;
User Instance=True;
MultipleActiveResultSets=True

I wonder why there's no Initial Catalog component to the connection string. 我想知道为什么连接字符串没有Initial Catalog组件。 You should determine the correct database within the MDF file to connect to, and include 您应该在MDF文件中确定要连接的正确数据库,并包括

Initial Catalog=MyDbName;

in the string. 在字符串中。 Immediately after the Integrated Security=True; 在“ Integrated Security=True;之后立即Integrated Security=True; piece will be a good place to put it. 件将是放置它的好地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM