2016-11-17 65 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

我真是太白癡了,我忘了在這裏添加這個類。我編輯了問題,請再次檢查。 –