Search code examples
asp.netentity-frameworklinq-to-sqllinq-to-entitiesentity-relationship

Insert record using entity Framework (database first)


there are 3 database tables (movies, reviews, users)

the reviews table include ( MemeberID, MovieID, Review Text, Rate, ReviewDate) (the MemeberID, and MovieID in the Review are the FK of the members table and the movies table) The Movie can have many reviews, and i'm trying to add review to a movie

even I have movie class and the member class, I have a problem, in order to insert review, i need to reference it to movie and users , link them, and i don't know how to do it

this code make a error:

" The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. "

This is my code...

public bool InsertNewReview(Movie _TheMovie, Member _TheMember, string _Text, byte _Rate, DateTime _ReviewDate)
    {

       Review ReviewToInsert = new Review()
            {
                MovieID = _TheMovie.MovieID,
                MemberID = _TheMember.MemberID,
                Movie = _TheMovie,
                Member =  _TheMember,
                Rate = _Rate,
                ReviewDate = _ReviewDate,
                ReviewText = _Text
            };

        videoLib.Reviews.AddObject(ReviewToInsert);
        videoLib.SaveChanges();

            return true;

    }

..

there are more data to insert to the Review class

Images: here

..

and the tables: (the "all columns" isn't a field in database tables)

Images: here


Solution

  • I got a solution, I need to define only the MovieID, MemberID, and not using their object

    and use try & catch, to detect if thier the same MovieID (fk) and MemberID (fk) in the same row (because the review don't have is own id in the database)

       public bool InsertNewReview(string _MovieID, int _MemberID, string _Text, byte _Rate, DateTime _ReviewDate)
        {
            try
            {
                Review ReviewToInsert = new Review()
                {
                    Rate = _Rate,
                    ReviewDate = _ReviewDate,
                    ReviewText = _Text,
                    MovieID = _MovieID,
                    MemberID = _MemberID
                };
    
                videoLib.Reviews.AddObject(ReviewToInsert);
                videoLib.SaveChanges();
                return true;
            }
    
            catch
            {
                return false;
            }
        }