gpt4 book ai didi

ASP.NET MVC 2 LINQ-to-SQL 生成的类和模型验证

转载 作者:行者123 更新时间:2023-12-02 10:00:38 26 4
gpt4 key购买 nike

我只是想确保我正确理解 ASP.NET MVC2 与 LINQ-TO-SQL 的最佳实践。

如果我在以下任何一点上有错误,请纠正我:

  • LINQ TO SQL 生成以下类:您,根据您的表格
  • 生成的类是模型
  • 这些是我们应该在 View 中使用的模型
  • 如果我们想向模型添加验证,我们可以扩展部分类并设置数据注释。类似于 this .

一般来说,我的问题是关于数据验证的。我过去所做的是为每个 LINQ-to-SQL 生成的类创建一个“影子”模型,并将数据验证放在那里。然后,在 Controller 中,我创建了“影子”模型的实例,并检索数据(使用存储库模式)。从实体映射到影子模型并将其传递到 View 。所以,类似的东西(在 Controller 中):

// Car is class generated by LINQ-to-SQL, based on the Car table
// Use repository class to retrieve the data (Car)
Car car = myDatabaseRepository.GetCar(1);

// CarModel is my 'shadow' model, which has all the data validation.
// For example, it makes sure Year is before 2010 (let's say).
CarModel carModel = new CarModel();
carModel.Year = car.Year;
carModel.Make = car.Make;
carModel.Model = car.Model;

return View(carModel);

这是错误的,对吧(没有双关语)?它应该只是:

// Car should have been extended (as partial) and data annotation
// should have been in the extended class, rather than a whole separate
// model class.
Car car = myDatabaseRepository.GetCar(1);
return View(car);

对吗?

最佳答案

我认为最好的做法是使用一个ViewModel(您称之为“影子”模型),用于仅将相关数据模型信息传递到 View 并合并 UI 验证元数据。您还可以使用诸如AutoMapper之类的库复制值,而不是手动编码每个值。

表 = 模型方法可以在非常简单的场景中工作(几个表+完全匹配数据库模式的简单 UI)。为了避免以后的麻烦,建议使用 ViewModel。

关于ASP.NET MVC 2 LINQ-to-SQL 生成的类和模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com