0

Model:

public class User {
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public virtual Membership Membership { get; set; }
}

public class Membership {
    public Guid UserId { get; set; }
    public DateTime CreateDate { get; set; }
}

DbContext:

public class UsersContext : DbContext {
    public UsersContext() : base("ApplicationServices") { }
    public DbSet<User> Users { get; set; }
    public DbSet<Membership> Memberships { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Entity<User>().ToTable("aspnet_Users");
        modelBuilder.Entity<Membership>().ToTable("aspnet_Membership");

        //insert relation here to join the two tables
    }
}

This is my first day playing around with the fluent api and i was just wondering how i would be able to join these two tables. How would i define the relation?

Also, any tutorials on the fluent API that have helped you?

theStig
  • 612
  • 1
  • 13
  • 33

1 Answers1

1

You could use next code example:

    modelBuilder.Entity<User>()
                .HasRequired(u=>u.Membership)
                .WithOptional()
                .HasForeignKey(u=>u.UserId)
Ben Cottrell
  • 5,741
  • 1
  • 27
  • 34
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • 1
    Got an error on HasForeignKey 'System.Data.Entity.ModelConfiguration.Configuration.ForeignKeyNavigationPropertyConfiguration' does not contain a definition for 'HasForeignKey' and no extension method 'HasForeignKey' accepting a first argument of type 'System.Data.Entity.ModelConfiguration.Configuration.ForeignKeyNavigationPropertyConfiguration' could be found (are you missing a using directive or an assembly reference?) – theStig Jul 29 '12 at 18:47
  • Ok. Don't use HasForeignKey(u=>u.UserId). You need it when you have one-to-many relationship. EntityFramework will use as ForeignKey the Key of optional table (in this example - it will be key of User) – Kirill Bestemyanov Jul 29 '12 at 22:26
  • Yup, thanks that does the trick, Also this works as well: modelBuilder.Entity().HasOptional(u => u.Membership).WithRequired(); – theStig Jul 30 '12 at 00:21