Search code examples
asp.net-mvcfluent-interface

one to one relationship with fluent api


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?


Solution

  • You could use next code example:

        modelBuilder.Entity<User>()
                    .HasRequired(u=>u.Membership)
                    .WithOptional()
                    .HasForeignKey(u=>u.UserId)