Tom*_*Aro 9 c# asp.net asp.net-mvc asp.net-mvc-4
我只是想创建一个可以使用两个模型的控制器.评论模型:
public class Comment
{
public int ID { get; set; } // property
public int PostID { get; set; }
public String Title { get; set; }
public String Name { get; set; }
public Uri Url { get; set; }
public String Text { get; set; }
public Post Post { get; set; }
}
public class CommentDBContext : DbContext
{
public DbSet<Comment> Comments { get; set; }
public System.Data.Entity.DbSet<BlogShauli.Models.Post> Posts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
邮政模式:
public class Post
{
public int ID { get; set; } // property
public String Title { get; set; }
public String Author { get; set; }
public String AuthorSite { get; set; }
public DateTime ReleaseDate { get; set; }
public String Text { get; set; }
}
public class PostDBContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个可以同时使用这两种模型的单一控制器.我读到这样做的方法是使用ViewModel Pattern,所以我创建了另一个名为" BlogViewModel.cs "的模型类,其代码如下:
public class MotorcycleViewModel
{
public Comment CommentPointer { get; set; }
public Post PostPointer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但从这里我不明白做什么.我正在尝试使用Entity框架创建一个新的Controller,但我不知道在"数据上下文类"中要选择什么.谁能解释我如何在两个模型和控制器之间建立连接?谢谢!
小智 1
请在您的存储库类中尝试以下操作 -
public MotorcycleViewModel GetModelData(int commentId, int postId)
{
MotorcycleViewModel result =new MotorcycleViewModel();
using (var context = new CommentDBContext())
{
var post = (from pst in context.Post where pst.ID == postId select pst).FirstOrDefault();
var comment = (from cmt in context.Comment where cmt.ID == commentId select cmt).FirstOrDefault();
result.CommentPointer = comment;
result.PostPointer = post;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
请点击链接查看如何从模型到视图模型进行转换,反之亦然
归档时间: |
|
查看次数: |
1559 次 |
最近记录: |