来自存储过程的 ASP.NET MVC 部分模型绑定

发布于 2024-09-11 19:46:54 字数 375 浏览 7 评论 0原文

目前,我有一组存储过程,调用它们来填充页面上的不同字段。我正在从 LINQ to SQL 类中调用存储过程,并将其放入其中,效果很好。但是,它会自动生成我必须使用的 (StoredProcedureName)Result 类名称。

无论如何,是否可以采用存储过程并将结果绑定到多个类?例如,我有一个存储过程,用于获取博客文章的信息。我想将该数据绑定到 Post 类和 User 类(对于作者而言),但是我没有从存储过程中检索所有数据来填充整个 Post 对象或 User 对象(存储过程仅返回标题、内容和作者姓名)。

处理这种情况的最佳方法是什么?我愿意更改存储过程,但我宁愿不必返回我不会仅用于填充完整对象的数据,而且我不能使用 LINQ to SQL 查询数据库。

Currently, I have a set of stored procedures which are called to populate different fields on a page. I am calling the stored procedures from the LINQ to SQL class that I dropped them on, which works fine. However, it automatically generates (StoredProcedureName)Result class names which I have to work with.

Is there anyway to take a stored procedure and bind the result to multiple classes? For example I have a stored procedure that gets the information for a blog post. I want to bind that data into a Post class and a User class (for the author), however I am not retrieving all of the data from the stored procedure to fill an entire Post object or User object (the stored procedure only returns the title, content, and author name).

What is the best way to handle this scenario? I am open to changing the stored procedure but I would rather not have to return data that I am not going to use just to populate a full object and I cannot use LINQ to SQL to query the database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初与友歌 2024-09-18 19:46:55

您可以创建 DataContext 的一部分并编写一个返回 IMultipleResults 的方法,使用 [ResultType(typeof(ClassName))] 绑定到每个相应的类,如下所示

: microsoft.com/en-us/library/bb399371.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb399371.aspx

或者,您可以存储结果变量中的存储过程,然后使用 LINQ 选择目标类的新实例,如下所示:

var result = dataContext.your_stored_proc();

var post = result.Select(s => new Post { Id = result.Id, Title = result.Title });

You can create a partial of your DataContext and write a method that returns IMultipleResults, binding to each of your respective classes with a [ResultType(typeof(ClassName))], as shown here:

http://msdn.microsoft.com/en-us/library/bb399371.aspx

Or, you can store the results of the stored procedure in a variable and then LINQ-Select new instances of your target classes like this:

var result = dataContext.your_stored_proc();

var post = result.Select(s => new Post { Id = result.Id, Title = result.Title });
咆哮 2024-09-18 19:46:55

您可以使用这个库:
https://github.com/mrmmins/C-StoreProcedureModelBinding

这些类正在使用反射,并且您需要将其包含在您的项目中并创建 Generic.cs 的实例

You can use this library:
https://github.com/mrmmins/C-StoreProcedureModelBinding

This classes are using reflection, and you need include it in your project and create an instance of Generic.cs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文