How to add foreign keys in EF 7 alpha

How to create a one-to-one relationship in EF 7 alpha3?

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

Can anyone shed some light on this?

+5
source share
2 answers

Until recently, there were no model builder APIs for defining relationships. Instead, you need to manipulate the base 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 learn more about our current (starting from 2014-07-31) thinking about how these APIs will look . The end result will look something like this.

 modelBuilder.Entity<Blog>() .OneToMany(b => b.Posts, p => p.Blog).ForeignKey(b => b.BlogId); 
+2
source

Using EF7 beta7, a new set of methods is introduced to determine the relationships between objects.

For relationships from one to several,

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

With .Reference(typeof(Blog), "Blog") settings .Reference(typeof(Blog), "Blog") from Entity Post to Blog . The first argument is the type of object that will set the goals, and the second argument is the name of the navigation property.

Using .InverseCollection("Posts") , a one-to-many relationship is configured. The argument to this function is the name of the navigation collection.

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

0
source

Source: https://habr.com/ru/post/1202080/


All Articles