【发布时间】:2015-12-12 13:02:52
【问题描述】:
我在将代码从数据库优先更改为代码优先时遇到了麻烦。我正在实施这篇博文http://techbrij.com/facebook-wall-posts-comments-knockout-aspnet-webapi。 第一个问题是首先从代码生成的数据库。它在数据库中创建两个用户配置文件表。第一个是单数,另一个是 Plurized。
注册时创建单数(UserProfile 表)(使用简单会员)。 我的 Post 类是这样的----
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int PostedBy { get; set; }
public System.DateTime PostedDate { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
}
} 我的 Post Comment 类是这样的----
public class PostComment
{
[Key]
public int CommentId { get; set; }
public int PostId { get; set; }
public string Message { get; set; }
public int CommentedBy { get; set; }
public System.DateTime CommentedDate { get; set; }
public virtual Post Post { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
而我的 UserProfile 类是这样的----
public class UserProfile
{
public UserProfile()
{
this.PostComments = new HashSet<PostComment>();
this.Posts = new HashSet<Post>();
}
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string AvatarExt { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
而我的 DbContext 是这样的---
public class WallEntitiesDbContext : DbContext
{
public WallEntitiesDbContext():base("WallEntitiesDbContext")
{
}
public DbSet<PostComment> PostComments { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
public override int SaveChanges()
{
return base.SaveChanges();
}
}
和我的连接字符串是这样的----
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=DBWallPostByTechBrij;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
我应该进行哪些更改,以便在数据库中只创建一个 UserProfile 表,并且 WallEntitiesDbContext 应该能够从数据库中的该表中检索信息。 现在,如果我删除-----
DbSet<UserProfile> UserProfiles {get; set;}
然后我的 wallpostController 开始出现错误。如果有人可以帮助我首先使用代码进行此操作,那将是很大的帮助。还有一件事,我已经手动将一些示例数据输入到数据库中,因此,登录后它应该显示来自数据库的帖子和 cmets,但它没有显示,如果我试图发布一些东西,它在这一行抛出异常 System.Data.Infrastructure.DbUpdateException----
public override int SaveChanges()
{
return base.SaveChanges();
}
在 WallEntitiesDbContext 类中。 Plzzz 任何人都可以看看它。我应该进行哪些更改才能使其正常工作。
【问题讨论】:
标签: asp.net-mvc-4 entity-framework-4 code-first simplemembership ef-database-first