开发者

EntityFramework CodeFirst FK association problem

开发者 https://www.devze.com 2023-02-18 22:26 出处:网络
I\'m trying to get CodeFirst working, and am having a problem with foreign keys and related objects.It is likely due to my not matching the \"convention\" and not yet understanding how to properly ove

I'm trying to get CodeFirst working, and am having a problem with foreign keys and related objects. It is likely due to my not matching the "convention" and not yet understanding how to properly override the conventions in my setup. Please help if you can.

I have these two tables in my existing database:

create table locations
(
ID int identity primary key
, name varchar(50) not null
)

create table meetings
(
ID int identity primary key
, whatever varchar(50) null
, LocationID int not null constraint FK_meetings_LocationID foreign key references locations(ID)
)

And the models are set up like so:

public class Location
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Meeting> Meetings { get; set; }
}

public class Meeting
{
    public int ID { get; set; }
    public string Whatever{ get; set; }
    public Location HeldAt { get; set; }
}

Finally, my context is set up like this:

public class v1Context : DbContext
{
    public v1Context(string ConnectionString)
        : base(ConnectionString)
    {}

    public DbSet<Location> Locations { get; set; }
    public DbSet<Meeting> Meetings { get; set; }

    //protected override void OnModelCreating(DbModelBuilder modelBuilder)
    //{
    //    modelBuilder.Entity<Location>().HasKey(k => k.ID);
    //    modelBuilder.Entity<Meeting>().HasKey(k => k.ID);
    //}
}

And, I'm getting the following error "An error occurred while executing the command definition. See the inner exception for details".. With an InnerExceptin of:

InnerException = {"Invalid column name 'HeldAt_ID'."}

I've tried various incantations of OnModelCreating, without any success. It looks obvious that the problem is that it doesn't know how to navigate the "LocationID" FK properly to the Location class with its ID field. But I've been unable to get it figured out.

Somehow I thought that since it was of type "Location" and that the Location class was also independently ma开发者_开发知识库pped to the database, and because there were proper FK relationships in the databse, that it would just "figure it out."

Any help would be greatly appreciated.


You don't use default names for columns so you must specify them in OnModelBuilding:

Use this to define LocationID as your foreign key column instead of default expected HeldAt_ID:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Meeting>()
        .HasRequired(m => m.HeldAt)
        .WithMany(l => l.Meetings)
        .Map(m => m.MapKey("LocationID"));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消