本文介绍了实体框架未能检索由于数据异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的两个波苏斯:

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; }
}

基类是只是有一个属性INT ID的类。

Base class is just a class that has a property int id.

在数据库中,有一个电影表和演员表一表MovieActor充当许多一对多关系表。目前,我在让所有的参与者对于一个给定的电影只是兴趣。但每当的DbContext试图访问的信息,我不断收到此异常:

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.

[ForeignKey("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-首先约定将创建之间存在一个一对多的关系的电影演员。既然你要一个多一对多的关系,你必须用流利的API配置此:

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
            });
    }
}

这篇关于实体框架未能检索由于数据异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:46