how to add foreign keys in EF 7 alpha

entity-framework-core

Question

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?

Accepted Answer

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);

Popular Answer

With EF7 beta7, new set of methods are introduced for defining relationships between entities.

For one to many relationship,

modelBuilder.Entity<Post>()
   .Reference(typeof(Blog), "Blog")
   .InverseCollection("Posts")
   .ForeignKey(new string[] { "BlogId" });

With, .Reference(typeof(Blog), "Blog") relationship from Entity Post to Blog is configured. First arguament is the type of the entity that Post targets and second arguament is the name of the navigation property.

With, .InverseCollection("Posts"), one to many relationship is configured. Arguament to this function is the name of the navigation collection.

With, .ForeignKey(new string[] { "BlogId" }), foreign key is configured. If this foreign key is not set, then shadow foreign key is automatically generated for you.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why