Insert record using entity Framework (database first)

asp.net entity-framework entity-relationship linq-to-entities linq-to-sql

Question

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

1
2
11/7/2012 1:07:51 AM

Accepted Answer

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;
        }
    }
0
11/9/2012 7:22:58 PM

Popular Answer

could you try like this

Review ReviewToInsert = videoLib.Reviews.CreateObject();
ReviewToInsert.MovieID = _TheMovie.MovieID
...
...
videoLib.Reviews.AddObject(ReviewToInsert);
videoLib.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow