【问题标题】:ASP.NET MVC 2 LINQ-to-SQL generated classes and Model ValidationASP.NET MVC 2 LINQ-to-SQL 生成的类和模型验证
【发布时间】:2010-01-12 19:38:07
【问题描述】:

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

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

  • LINQ TO SQL 生成类 你,根据你的表
  • 生成的类是模型
  • 这些是我们应该在视图中使用的模型
  • 如果我们想为模型添加验证,我们扩展部分类并设置数据 注释。类似于 this

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

// 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);

对吗?

【问题讨论】:

  • 对。模型元数据类甚至不必定义数据类型。
  • LukLed,你是什么意思?可以举个例子吗?
  • @An Idiot:看教程中的例子。 MetaData 类中定义的类型被定义为对象,类型不是必需的,您应该只使用此类来描述您的模型。它也可以是嵌套类。没什么好说的了:)你的代码中仍然使用Car类,而不是CarMetadata
  • @LukeLed,明白了,抱歉,我最初在示例中没有注意到它。现在就像一个魅力。

标签: asp.net asp.net-mvc linq-to-sql model


【解决方案1】:

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

Table = Model 方法可以在非常简单的场景中工作(很少的表 + 与数据库架构完全匹配的简单 UI)。为了在以后避免很多痛苦,建议使用 ViewModels。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多