C# ORM代码优先-在设计期间修复

C# ORM代码优先-在设计期间修复,c#,asp.net-mvc,entity-framework,ef-code-first,C#,Asp.net Mvc,Entity Framework,Ef Code First,我在理解MVC4简单web应用程序中的对象关系映射时遇到了一点困难,其中有用户及其发布的评论。 一个用户必须有很多评论。因此,我在我的UsersContextclasspublic DbSet UserComments{get;set;} public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } public DbSe

我在理解MVC4简单web应用程序中的对象关系映射时遇到了一点困难,其中有用户及其发布的评论。 一个用户必须有很多评论。因此,我在我的
UsersContext
class
public DbSet UserComments{get;set;}

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<UserWork> UserComments { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int? UserComId { get; set; }
    [ForeignKey("UserComId")]
    public virtual UserComment UserComLog { get; set; }        
}
public class UserComment 
{
    [Key]
    public int UserComId{ get; set; }
    public int UserId { get; set; }        
    public string Comments{ get; set; }
    public DateTime postDate{get;set}
}
public类用户上下文:DbContext
{
公共用户上下文()
:base(“默认连接”)
{
}
公共数据库集用户配置文件{get;set;}
公共DbSet UserComments{get;set;}
}
[表(“用户档案”)]
公共类用户配置文件
{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId{get;set;}
公共字符串用户名{get;set;}
公共字符串名{get;set;}
公共字符串LastName{get;set;}
public int?UserComId{get;set;}
[外键(“UserComId”)]
公共虚拟用户comment UserComLog{get;set;}
}
公共类UserComment
{
[关键]
public int UserComId{get;set;}
public int UserId{get;set;}
公共字符串注释{get;set;}
public DateTime postDate{get;set}
}

我现在一直在想,每天发布的所有评论都是如何存储的,这样我以后就可以在UserComment.UserId=UserProfile.UserId中从UserComment内部加入UserProfile进行查询,其中postDate介于(…)和(…)

我假设您使用的是代码优先迁移

似乎您需要稍微编辑一下
UserProfile
类,以允许用户有多个注释。您需要将
UserComLog
设置为一个集合。比如:

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<UserComment> UserComLog { get; set; }        
}

comments
将是一个
IQueryable
,您可以将其传递到一个循环中以显示在页面上,或者根据需要进一步过滤。

此模型是生成的,还是您创建了类?您是否先使用EF代码?通常,您的
UserProfile
上会有属性
public virtual ICollection UserComments
var context = new UsersContext();
var comments = context.UserComments.Where(d => d.postDate > new DateTime(2013,3,12) && d.postDate < new DateTime(2013,2,12) && d.UserId == userId);