C# 实体框架7关系
我使用下面的示例来测试asp.net 5和EF7:C# 实体框架7关系,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我使用下面的示例来测试asp.net 5和EF7: using Microsoft.Data.Entity; using System.Collections.Generic; namespace EFGetStarted.AspNet5.Models { public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public D
using Microsoft.Data.Entity;
using System.Collections.Generic;
namespace EFGetStarted.AspNet5.Models
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Make Blog.Url required
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
您应该为导航属性指定
virtual
关键字。这是因为EF创建代理对象(即类的继承者)来实现延迟加载。这些继承者只能覆盖您的虚拟属性:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}
很好的答案解释了为什么它会工作,而不仅仅是说“做这个:uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?如果我需要使用其他名称(如OldPosts),该怎么办?@paulo你可以使用任何你喜欢的名称。EF将为您生成id属性。这些属性可以有OldPosts\u Id等名称。如果您想控制这些名称,您可以在Blog或Post之类的类中手动指定它们,然后您应该修改OnModelCreating方法以配置映射/导航属性匹配。真正的问题是EF 7还不支持关系。@正如我所见,EF团队已经完成了该功能,:Implemented。。。基于导航和外键属性的实体之间的关系。我明天可以查看。作为答案链接的问题不相关,因为这是关于EntityFramework7的,链接的问题适用于以前的版本。
myBlog.Posts
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}
// This statement fills Posts property:
var blog = dbContext.Blogs.Include(x => x.Posts).FirstOrDefault(x => x.Id == id);