0

I built a code-first database, I am using Entity Framework, and it was all going well until I went inside the database through SQL Server explorer.

I found out that inside my objects, the navigation properties are not there. In the code, they act fine and Visual Studio auto completes on these navigation properties, but inside the database, physically there is no column for them or any kind of mention. They appear in the .edmx diagram and all looks fine.

I tried building the db from the top but still doesn't work. The database is saved inside my project ./bin/debug directory. Any ideas why?

It is basically a list of movies and actors, when I try to add movie to a list of movies that the actor object contains, it just doesn't show in the database.

Another question: I want to search in database for an object and when I find it I want to get the object itself with its own type and use it.

When I try to use

var query2 = (from b in ctx.Actors
              where (b.FirstName == f && (b.LastName) == l)
              select b).Take(1);    // assert that only one is chosen

// Oscar.BestActor = query2.ToList();
Oscar.BestActor = (Actor)query2;

// not sure about this line (ctx.entry...) - am I doing this right?
ctx.Entry(Oscar.BestActor).State = System.Data.Entity.EntityState.Modified;

ctx.SaveChanges();

I get this error:

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[QueryMoviesFinal.Actor]' to type 'QueryMoviesFinal.Actor'.

Thanks for taking the time and read this !

6
  • The SQL only has the database which is the mdf file. All the c# connections properties are part of the Visual Studio Project. Commented Jun 8, 2018 at 18:35
  • Well, if you have a many-to-many relationship between Movie and Actor (a movie has several actors, and each actor can play in several movies), then EF will use a link table between these two base tables to model this m:n relationship. This is a separate table that usually only contains the primary keys (the ID) of each entity - so it might contain a MovieId and an ActorId, and it will have a name of its own. Check if you find such a table! Commented Jun 8, 2018 at 19:09
  • Can you please show us the model classes for Movie and Actor ?? Commented Jun 8, 2018 at 19:11
  • You're asking two very different questions here. Which one should it be? Commented Jun 8, 2018 at 20:12
  • it is many to many Commented Jun 8, 2018 at 22:30

1 Answer 1

2

.Take returns a sequence. You want to use .Single().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.