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.

Answers


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.


Need Your Help

dropbox api output needs to be changed in my code

php dropbox-api

I am using php sdk provided by Dropbox Core API. Everything is working fine... but need to update the output... I am getting image's name as an output... But I need to diaplay images itself...

SQLite3: Batch Insert?

iphone database sqlite core-data ios

I've got some old code on a project I'm taking over.