简体   繁体   中英

EF4 Code-First CTP5 Many-to-one

I've been trying to get EF4 CTP5 to play nice with an existing database, but struggling with some basic mapping issues.

I have two model classes so far:

public class Job
{
    [Key, Column(Order = 0)]
    public int JobNumber { get; set; }
    [Key, Column(Order = 1)]
    public int VersionNumber { get; set; }

    public virtual User OwnedBy { get; set; }
}

and

[Table("Usernames")]
public class User
{
    [Key]
    public string Username { get; set; }

    public string EmailAddress { get; set; }

    public bool IsAdministrator { get; set; }
}

And I have my DbContext class exposing those as IDbSet

I can query my users, but as soon as I added the OwnedBy field to the Job class I began getting this error in all my tests for the Jobs:

Invalid column name 'UserUsername'.

I want this to behave like NHibernate's many-to-one, whereas I think EF4 is treating it as a complex type. How should this be done?

UserUsername is the default name that EF Code First chooses for the foreign key in the Jobs table. Obviously, it's not the same name that your existing database has for the FK column in Jobs table. You need to override this conventions and change the FK's default name so that it matches your database. Here is how it's done with fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Job>()
                .HasOptional(j => j.OwnedBy)
                .WithMany()
                .IsIndependent()
                .Map(m => m.MapKey(u => u.Username, "TheFKNameInYourDB"));
}

Try let it create new database from your schema and look what columname it expect.

I think its foreing key for OwnedBy. It tries to name it according to its internal convention, that is incompatible with how you named your foreing key column. And no, its really treating it as many-to-one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM