IPValverde
IPValverde

Reputation: 2029

EF 4.1 not respecting the SQL Server columns

I have just updated my MVC3 project (with C#) from ObjectContext to DbContext, but I'm getting some weird error...

I'm using the database-first approach, and I have an table with a Name column of type nvarchar, that was not null. I changed it to accept null in SQL Server, then I updated my edmx model, deleted the .tt files and generated it again (with ADO.NET DbContext).

When I create a new object from that table, setting value to Name property to null I get an DbEntityValidationException with The Name field is required message in db.SaveChanges().

But the table is accepting NULL on Name column! I already inserted many rows with SQL in SQL Server with NULL in Name column!

Anyone knows how can I solve that?

Some information

Here is my table SQL:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Pre_Register](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](64) NULL,
    [Email] [nvarchar](64) NOT NULL,
    [Permission] [tinyint] NOT NULL,
    [Password] [nvarchar](256) NOT NULL
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

This is the automatic generated model class:

public partial class Pre_Register
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public byte Permission { get; set; }
    public string Password { get; set; }
}

And here is how I get the error:

Pre_Register preReg = new Pre_Register();

db.Pre_Register.Add(preReg);

preReg.Email = "[email protected]";
preReg.Permission = 1;
preReg.Password = "123456";
preReg.Name = null;

// here it comes
db.SaveChanges();

Upvotes: 2

Views: 212

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

The only thing i see :

Open your edmx.

Go to your Pre_Register entity, select your Name property, right click, properties, and check if Nullable field is set to true.

If it's not, set it to true. This would be strange, but I can't find another reason.

enter image description here

This would mean that DataBase first is... not perfect, or that something happened on your side...

Upvotes: 1

Related Questions