Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Insert First Set of Data To EF Code-First Using Repository Pattern.

i am trying to insert first set of data to database using Entity Framework Code-First And generic repository pattern. My POCO classes have these relations:

Here are my POCO classes:

public class Student : EntityBase
{
    public Student()
    {
        this.Lessons = new HashSet<Lesson>(); 
    }

    public string Name { get; set; }

    //FK Collage
    public int CollageId { get; set; }

    public virtual ICollection<Lesson> Lessons { get; set; }
    public virtual Collage Collages { get; set; }
}

public class Lesson : EntityBase
{
    public Lesson()
    {
        this.Students = new HashSet<Student>(); 
    }

    public string Name { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

public class Collage : EntityBase
{
    public Collage()
    {
        Students = new List<Student>(); 
    }
    public string Name { get; set; }


    public virtual ICollection<Student> Students { get; set; }

}

Here is my Mappings:

public class StudentMap : EntityTypeConfiguration<Student>
{
    public StudentMap()
    {
        //ToTable("TblStudent");

        HasRequired<Collage>(x => x.Collages)
            .WithMany(e => e.Students)
            .HasForeignKey(i => i.CollageId)
            .WillCascadeOnDelete(false);

        HasMany<Lesson>(x => x.Lessons)
            .WithMany(e => e.Students)
            .Map(i =>
            {
                i.MapLeftKey("StudentFKId");
                i.MapRightKey("LessonFKId");
                i.ToTable("TblStudent_Lesson");
            });

    }
}

Now in my Controller:

public ActionResult Index()
{
    Repository<Student> _reStu = new Repository<Student>();
    _reStu.Add(new Student { Name = "Test", CollageId = 0, Collages = null, Lessons = null });
    _reStu.save();

    return View();
}

I get this Error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.TblCollage_CollageId". The conflict occurred in database "test2", table "dbo.TblCollage", column 'Id'. The statement has been terminated.

I know that i have a relation between tables but how can i insert the first set of data when there is a relation? should i include my relation after i pass the data within?

Upvotes: 0

Views: 301

Answers (2)

smoksnes
smoksnes

Reputation: 10851

how can i insert the first set of data when there is a relation?

CollageId is a non-nullable column, which means that you need to set it. Currently your model says that every Student must have one College, so SQL Server will not allow you to insert an invalid row.

So in order to add any Student you need to add a College first.

should i include my relation after i pass the data within?

EF is pretty smart, so you should be able to go with either of these approaches.

Create the College while you create the Student.

Repository<Student> _reStu = new Repository<Student>();
_reStu.Add(new Student { Name = "Test", Collages = new College { Name = "TestCollege" }, Lessons = null });
_reStu.save();

Or create the College first, and then the Student.

Repository<College> _reColl = new Repository<College>();
var college = new College
{
    Name = "TestCollege"
};
_reColl.Add(college)
_reColl.save();

// As long as you have the same reference your college will get an Id after you inserted it.

Repository<Student> _reStu = new Repository<Student>();
_reStu.Add(new Student { Name = "Test", CollegeId = college.Id, Lessons = null });
_reStu.save();

Upvotes: 1

ilya korover
ilya korover

Reputation: 230

It looks like you should add an existing CollageId to your Student object or you should create a new Collage (if it's necessary) object and set it as Collage property of the Student object.

The reason of that error is database constraint which doesn't allow to add students without CollageId set, but you try to save a student without Collage (CollageId = 0).

Upvotes: 1

Related Questions