Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add foreign keys in EF 7 alpha

How do I make a one-to-one relationship in EF 7 alpha3?

The old way of just defining navigation properties does not work, and the modelBuilder does not have the previously used HasRequired/HasOptional methods.

Can anyone shed some light on that?

like image 642
Chris Avatar asked Oct 31 '22 17:10

Chris


1 Answers

Until recently, there weren't any model builder APIs for defining relationships. Instead, you have to manipulate the underlying modelBuilder.Model object. Here is an example of a one-to-many relationship.

class Blog
{
    public Blog()
    {
        Posts = new List<Post>();
    }

    public int Id { get; set; }

    public ICollection<Post> Posts { get; set; }
}

class Post
{
    public int Id { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Post>().ForeignKeys(x => x.ForeignKey<Blog>(p => p.BlogId));

        var model = builder.Model;
        var blog = model.GetEntityType(typeof(Blog));
        var post = model.GetEntityType(typeof(Post));
        var fk = post.ForeignKeys.Single(k => k.ReferencedEntityType == blog);
        blog.AddNavigation(new Navigation(fk, "Posts", pointsToPrincipal: false));
        post.AddNavigation(new Navigation(fk, "Blog", pointsToPrincipal: true));
    }
}

You can read more about our current (as of 2014-07-31) thinking for what these APIs will look like. The end result would look something like the following.

modelBuilder.Entity<Blog>()
    .OneToMany(b => b.Posts, p => p.Blog).ForeignKey(b => b.BlogId);
like image 194
bricelam Avatar answered Dec 15 '22 01:12

bricelam