简体   繁体   中英

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. But I can not get it to resolve within my controller when I use the .include() command. Here is the code.

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

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

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

我的SQL Server 2012数据库中的关系

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM