Here are my two POCOs:
[Table("Movie", Schema= "dbo")]
public class Movie: BaseClass
{
public string TitleName { get; set; }
public virtual ICollection<Actor> Actor{ get; set; }
}
[Table("Actor", Schema="dbo")]
public class Actor: BaseClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? BirthDate { get; set; }
}
Base class is just a class that has a property int id.
In the database, there's an Movie table and an Actor table with a MovieActor table to act as the many-to-many relationship table. Currently, I'm just interested in getting all the actors for a given movie. But whenever the dbcontext tries to access the information, I keep getting this exception:
"InnerException = {"Invalid column name 'Movie_Id'.\r\nInvalid column name 'Movie_Id'.\r\nInvalid column name 'Movie_Id'."}"
I searched StackOverflow for a similar issue and they suggested (to the other user) to use a foreign key, so I created an attribute in front of the Actor collection.
[Fo开发者_StackOverflow社区reignKey("Actor")]
And then I get another exception that says:
The ForeignKeyAttribute on property 'Actor' on type
'Movie' is not valid. The foreign key name
'Actor' was not found on the dependent type
'Actor'.
The Name value should be a comma separated list of foreign key property names.
Has anybody here run across this problem before?
EF 4.1 Code-First conventions would create a one-to-many relationship between Movie
and Actor
. Since you want a many-to-many relationship you must configure this with Fluent API:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>()
.HasMany(m => m.Actor)
.WithMany()
.Map(a => {
a.MapLeftKey("MovieId"); // your PK column name in Movie table
a.MapRightKey("ActorId"); // your PK column name in Actor table
a.ToTable("MovieActor"); // your join table name
});
}
}
Please see this post for more help. I think it will help explain how to do this. You have to scroll down to get to the foreign key portion. It basically says:
With foreign keys, they can either be exposed in the model or not. When I say “exposed in the model”, it means there is an additional property on the dependent entity that is the value of the principal entity. In the code below, the property PrimaryCategoryCode is an exposed foreign key of Primary Category.
public string PrimaryCategoryCode { get; set; } public virtual Category PrimaryCategory { get; set; }
To indicate this, use the ForeignKey attribute on the PrimaryCategory property as follows:
public string PrimaryCategoryCode { get; set; } [ForeignKey("PrimaryCategoryCode")] public virtual Category PrimaryCategory { get; set; }
精彩评论