[英]ASP.Net MVC Entity Framework Relationships
From what I understand I am doing this correctly. 据我了解,我正在正确地做到这一点。 I have a blog table with a relationship of CategoryId on the table Category's id field.
我有一个博客表,该表在表Category的id字段上具有CategoryId的关系。 But I can not get it to resolve within my controller when I use the .include() command.
但是当我使用.include()命令时,无法在控制器中解析它。 Here is the code.
这是代码。
Blog.cs Blog.cs
public class Blog
{
[Key]
public int Id { get; set; }
[Required, StringLength(50)]
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime PostedDate { get; set; }
[Required]
public string Meat { get; set; }
[Required, StringLength(25)]
public int CategoryId { get; set; }
public string FriendlyUrl { get; set; }
public virtual ICollection<Category> Category { get; set; }
}
public partial class BlogDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
Category.cs Category.cs
public class Category
{
[Key]
public int Id { get; set; }
[Required, StringLength(50)]
public string Title { get; set; }
public string FriendlyUrl { get; set; }
}
public partial class BlogDbContext : DbContext
{
public DbSet<Category> Categories { get; set; }
}
BlogController BlogController
public class BlogController : Controller
{
private readonly BlogDbContext _db = new BlogDbContext();
public ActionResult Index()
{
var blogs = _db.Blogs.Include(c => c.Category); //This is where the error occurs
return View(blogs.ToList());
}
}
var blogs = _db.Blogs.Include("Category");
应该更好地工作。
Instead of 代替
public virtual ICollection<Category> Category { get; set; }
I think it should be 我认为应该
public virtual Category Category { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.