我的数据库中有两个表。第一个是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; }
}
}
MyCourse.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:更新条目时发生错误。有关详细信息,请参阅内部异常---&GT; System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束“FK__MyStudent__Cours__35BCFE0A”冲突。冲突发生在数据库“MyDB”,表“dbo.MyCourse”,列“Id”中。该语句已终止。在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolean breakConnection,Action 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)处于System.Data.SystemClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncClose) System.Data.SqlClient.SqlCommand.FinishExecuteReader中的.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean&amp; dataReady)(SqlDataReader ds,RunBehavior runBehavior,String resetOptionsString,Boolean isInternal,Boolean forDescribeParameterEncryption)System.Data.SqlClient上的System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean async,Int32 timeout,Task&amp; task,Boolean asyncWrite,Boolean inRetry,SqlDataReader ds,Boolean describeParameterEncryptionRequest) .SqlCommand.RunExecuteReader( CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String方法,TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource
1 completion,String methodName,Boolean sendToPipe,Int32 timeout,Boolean&amp;在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__0(DbCommand t,DbCommandInterceptionContext 1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher
的System.Data.SqlClient.SqlCommand.ExecuteNonQuery()中使用usedCache,Boolean asyncWrite,Boolean inRetry 1.Dispatch [TTarget, TInterceptionContext,TResult](TTarget target,Func 3 operation, TInterceptionContext interceptionContext, Action
3执行,Action 3 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(Dictionary
2 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, Func
2 updateFunction)在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter。在System.Data上的System.Data.Entity.Core.Objects.ObjectContext.b__35()处的System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction [T](Func 1 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](Func
1操作)处更新() System.Data.Entity.InternalContext.SaveChanges()<的System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions选项)中的.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options,Boolean executeInExistingTransaction) / p>
答案 0 :(得分:1)
看起来您有many-to-many
关系,但没有加入表格。您需要第三个表来存储Id
和MyStudent
表中的MyCourse
来映射记录。我不能保证语法100%正确,但这应该给你一个很好的主意。
CREATE TABLE [dbo].[MyStudent] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[MyCourse] (
[Id] INT NOT NULL,
[Title] NVARCHAR (50) NULL,
[StudentId] INT NULL,
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)
);
答案 1 :(得分:1)
默认情况下,连接表使用由关系两边的外键组成的复合键。您获得的错误意味着您已经为您尝试保存的特定组合输入了条目。现在,看起来你正在设置每个新学生的身份都是10,这在一开始就没有任何意义。当然,一旦你运行了一次,任何进一步的尝试都会产生这个错误,因为这个课程和一个id为10的学生之间已经存在关联。