开发者

Why is entity framework not annotating some non nullable columns as required?

开发者 https://www.devze.com 2023-03-18 16:55 出处:网络
I am using EF 4.1 with database first. Example table: CREATE TABLE dbo.Foo( [ID] [int] IDENTITY(1,1) NOT NULL,

I am using EF 4.1 with database first.

Example table:

CREATE TABLE dbo.Foo(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    Created datetime not null default(getdate()),
    Title varchar(80) not null

PRIMARY KEY CLUSTERED ([ID] ASC)
)

EF correctly loads the model with all 3 columns as nullable = false.

Output from code generation item "ADO.NET DbContext Generator":

 public partial class Foo
 {
    public int ID { get; set; }
    public System.DateTime Created { get; set; }
    public string Title { get; set; }
 }

In MVC3 I generate the FooController via the db context and foo model. When I bring up /Foo/Create and hit "Create" on the blank form it shows a validation error on "Created" field but not on "Title".

If I enter only a "created" date I get an exception:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

The exception is "The Title field is required".

I'm not sure why it works fine for one column but not the other. My first fix was to simply add the annotation, however the class code is auto generated by EF.

The only fix that seems to work is to use a partial metadata class: ASP.NET MVC3 -开发者_如何学编程 Data Annotations with EF Database First (ObjectConext, DbContext)

I can add the [Required] tag as desired however this should be unnecessary. Is this a bug in EF or am I just missing something?


This isn't a bug, EF simply doesn't add those attributes. As far as i know, the database-first approach (Entity classes generated by the designer) doesn't even perform the validation. The link you're refering to is a valid solution for your problem. The principle of buddy-classes which contain the actual metadata was introduced due to the fact, that you cannot add attributes to existing properties in a partial class.

The code-first approach has a built-in functionality to validate your annotations, see: Entity Framework 4.1 Validation. Another solution when using database-first would be to create a custom code-generator that applies those attributes T4 Templates and the Entity Framework.

0

精彩评论

暂无评论...
验证码 换一张
取 消