Search code examples
c#entity-frameworkentity-framework-4fluent-interface

EF 4.2 Code First, how to map with fluent API?


(Since i have a database predefined i can't let EF recreate it).

This the mapping i use now (works but i want to rewrite using fluent api):

public class League
{        
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid LeagueId { get; set; }
    ....
    #region References

    public virtual ICollection<News> News { get; set; } 

    #endregion
}

public class News
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid NewsId { get; set; }
    public Guid LeagueId { get; set; }
    ....
    #region References

    [ForeignKey("LeagueId")]
    public virtual League League { get; set; }

    #endregion
}

Now, how can i map this using the fluent API?

Update Wrote this and it works, but is there a simpler version?

modelBuilder.Entity<League>().HasMany(x => x.News).WithRequired(y => y.League).HasForeignKey(c => c.LeagueId);

Update 2 I added those missing from the classes. But the problem is that if i leave it at that and try it, it fails. I need to specify a key somewhere.I can't let EF create the database and it refuses to just operate with tables.


Solution

  • You should look at this article for example: http://www.codeproject.com/Articles/184133/Using-Entity-Framework-4-1-Code-First-with-an-exis The base part, is that you should remove default db initializer:

    Database.SetInitializer<YourContext>(null);
    

    And this should prevent EF from trying to change your db or throw errors. It will just try to work with what you give it.