Quantcast
Channel: Entity Framework
Viewing all articles
Browse latest Browse all 10318

Edited Unassigned: Migrations :: When adding new column to the database, we should scaffold AddColumn operation with a default value default(T) [1606]

$
0
0
Consider the following model:

```
public class Customer
{
public int Id { get; set; }
}

public class VipCustomer : Customer
{
public string Name { get; set; }
}

public class MyContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
```
Create migration:

```
Enable-Migrations
Add-Migration Mig1
Update-Database

```
Then run the following code:

```
using (var ctx = new MyContext())
{
var customer1 = new Customer();
var customer2 = new VipCustomer { Name = "Foo" };
var customer3 = new Customer();

ctx.Customers.AddRange(new Customer[] { customer1, customer2, customer3 });
ctx.SaveChanges();
}
```

Now, add new Int32 column to VipCustomer:

```
public class VipCustomer : Customer
{
public string Name { get; set; }
public int Discount { get; set; }
}
```

We scaffold the following migration:

```
AddColumn("dbo.Customers", "Discount", c => c.Int());
```

Now, if you try to query for Customers, you will get the following error:


__Unhandled Exception: System.Data.ConstraintException: The 'Discount' property on
'VipCustomer' could not be set to a 'null' value. You must set this property to
a non-null value of type 'System.Int32'.__

Users can work around this by specifying a default value in the migration manually, but we should consider adding a default default value (default(T)). This would break for DateTime on Sql Server, but should be a reasonable value for all other value types.

Also, this is a very common extensibility point for Identity, so people will hit that scenario a lot.

Note that this is only a concern in a scenario with inheritance. Otherwise we scaffold a non-nullable column, so the value that database inserts by default is fine.

Viewing all articles
Browse latest Browse all 10318

Trending Articles