2016-11-17 67 views
0

我的数据库中有两个表。第一个是MyStudent,另一个是MyCourse。我使用.net的entityframework,并在Visual Studio中创建了一个名为“BestModel”的模型。这是我的课程;在asp.net中创建新记录时出现错误Razor引擎

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);”一切安好。我认为问题是关于这两个表和外键之间的关系。请帮帮我 。 ..

EDIT

类之间的关系是多对多。 。 。

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.SqlConnection.OnError(SqlException异常,布尔breakConnection,动作1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction)在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔callerHasConnectionLock,布尔asyncClose)在System.Data.SqlClient.TdsParser .TryRun(runBehavior runBehavior,SqlCommand的cmdHandler,SqlDataReader的数据流,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,布尔& dataReady)在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader的DS,runBehavior runBehavior,字符串resetOptionsString,布尔isInternal,布尔forDescribeParameterEncryption)在系统.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔returnStream,布尔异步,Int32超时,任务&任务,布尔asyncWrite,布尔inRetry,SqlDataReader ds,布尔describeP ()方法返回一个字符串,这个字符串表示一个字符串,这个字符串表示一个字符串,这个字符串表示一个字符串,这个字符串表示一个字符串,这个字符串表示这个字符串的位置。 System.Data.SqlClient.SqlCommand.ExecuteNonQuery()在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__0(的DbCommand吨,DbCommandInterceptionContext 1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher 1.Dispatch [t目标,TInterceptionContext,TResult](t目标靶,函数功能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)at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()at System.Data.Entity.Core.Objects.ObjectContext.b__35()at 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 operation)at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options,Boolean executeInExistingTransaction)at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)at System.Data.Entity.Internal.InternalContext.SaveChanges()

+0

问题仍在进行中。请帮帮我 。 。 。 –

+0

你有没有进入InnerException?尝试了一个try-catch块? [此](http://stackoverflow.com/questions/11531769/saving-many-to-many-relationship-data-on-mvc-create-view)有帮助吗? –

+0

我编辑并添加了内部消息。 –

回答

1

默认情况下,连接表使用由关系两边的外键组成的组合键。您收到的错误意味着您已尝试保存特定组合的条目。现在,看起来你将每个新生的ID都设置为10,这首先没有任何意义。当然,一旦你运行一次,任何进一步的尝试都会产生这个错误,因为这个过程与id为10的学生之间已经存在关联。

1

看起来像你有many-to-many的关系,但没有加入表。您需要第三张表来存储IdMyStudentMyCourse表映射记录。我不能保证语法是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) 
); 
+0

我真是太白痴了,我忘了在这里添加这个类。我编辑了问题,请再次检查。 –