【发布时间】:2016-11-17 14:54:13
【问题描述】:
我的数据库中有两个表。第一个是 MyStudent,另一个是 MyCourse。我使用 .net 的实体框架,并在 Visual Studio 中创建了一个名为“BestModel”的模型。这是我的课;
MyStudent.cs
namespace tt.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class MyStudent
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MyStudent()
{
this.MyCourse = new HashSet<MyCourse>();
}
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("MyCourse")]
public Nullable<int> CourseId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MyCourse> MyCourse { get; set; }
}
}
我的课程.cs
namespace tt.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class MyCourse
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MyCourse()
{
this.MyStudent = new HashSet<MyStudent>();
}
public int Id { get; set; }
public string Title { get; set; }
[ForeignKey("MyStudent")]
public Nullable<int> StudentId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MyStudent> MyStudent { get; set; }
}
}
这是我的表定义;
CREATE TABLE [dbo].[MyStudent] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
[CourseId] INT NULL,
FOREIGN KEY (CourseId) REFERENCES MyCourse(Id),
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[MyCourse] (
[Id] INT NOT NULL,
[Title] NVARCHAR (50) NULL,
[StudentId] INT NULL,
FOREIGN KEY (StudentId) REFERENCES MyStudent(Id),
PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[MyStudentCourses] (
[CourseId] INT NOT NULL,
[StudentId] INT NOT NULL,
FOREIGN KEY (CourseId) REFERENCES MyCourse(Id),
FOREIGN KEY (StudentId) REFERENCES MyStudent(Id)
);
这是我的创建函数;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title")] MyCourse myCourse)
{
if (ModelState.IsValid)
{
MyStudent st = new MyStudent();
st.Id = 10;
st.CourseId = 1;
st.Name = "sadasd".ToString();
myCourse.MyStudent.Add(st); // when this line commented everything is fine.. .
db.MyCourse.Add(myCourse);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(myCourse);
}
我为上面的这个问题指定了感兴趣的线。当我想创建一条新记录时,它给了我“更新条目时发生错误。有关详细信息,请参阅内部异常。”但是当我禁用该行时“myCourse.MyStudent.Add(st);”一切安好。我认为问题在于这两个表和外键之间的关系。请帮我 。 ..
编辑
类之间的关系是多对多的。 . .
EDIT2
InnerException 是这样的;
System.Data.Entity.Core.UpdateException:更新条目时出错。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:INSERT 语句与 FOREIGN KEY 约束“FK__MyStudent__Cours__35BCFE0A”冲突。冲突发生在数据库“MyDB”、表“dbo.MyCourse”、列“Id”中。该语句已终止。在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔 breakConnection,Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) 在 System.Data.SqlClient System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,布尔异步,Int32 超时,任务和任务,布尔异步写入,布尔 inRetry,SqlDataReader ds,布尔 describeParameterEncryptionRequest)在 System.Data.SqlClient.SqlCommand.RunExecuteReader (钴mmandBehavior cmdBehavior,RunBehavior runBehavior,布尔返回流,字符串方法,TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 完成,字符串方法名,布尔 sendToPipe,Int32 超时,布尔和 usedCache,布尔 asyncWrite,布尔 inRetry) 在 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__0(DbCommand t, DbCommandInterceptionContext1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget 目标, Func3 operation, TInterceptionContext interceptionContext, Action3 执行, Action3 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary2 identifierValues, List 1 generatedValues) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() --- End of inner exception stack trace --- at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator ut) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func2 updateFunction) 在 System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() 在 System.Data.Entity.Core.Objects.ObjectContext.b__35() 在 System.Data.Entity.Core.Objects .ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) at System.Data.Entity.Core.Objects.ObjectContext.Save System.Data.Entity.Internal.InternalContext.SaveChanges() 处的更改(SaveOptions 选项)
【问题讨论】:
-
问题仍在处理中。请帮我 。 . .
-
你进入 InnerException 了吗?尝试了 try-catch 块? this 有帮助吗?
-
我编辑并添加了内部消息。
标签: c# asp.net-mvc razor