Kewin Rather Kewin Rather - 23 days ago 7
C# Question

Error when creating a new record in asp.net Razor Engine

I have two tables in my database. First one is MyStudent and the other one is MyCourse. I use the entityframework of .net and in Visual Studio I created a model which is called "BestModel". Here is my classes;

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; }
}
}


Here is my table definitions;

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)
);


and Here is my Create Function;

[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);
}


I specified the line of interest for this problem above. When I want to create a new record it gives me "An error occurred while updating the entries. See the inner exception for details." But when I disabled that line "myCourse.MyStudent.Add(st);" everything is fine. I think the problem is about the relationship between these two tables and foreign keys. Please help me . ..

EDIT

The relationship between classes is many to many . . .

EDIT2

InnerException is like that;

System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__MyStudent__Cours__35BCFE0A". The conflict occurred in database "MyDB", table "dbo.MyCourse", column 'Id'. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, 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& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__0(DbCommand t, DbCommandInterceptionContext
1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher
1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func
3 operation, TInterceptionContext interceptionContext, Action
3 executing, 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()

Answer

By default, the join table uses a composite key composed of the foreign keys of the two sides of the relationship. The error you're getting means that there's already an entry for the particular combination you're trying to save. Right now, it looks like you are setting every new student's id to be 10, which doesn't make any sense in the first place. Definitely, once you've run this once, any further attempts will generate this error, though, because there will have already been an association between this course and a student with id of 10.