dotnet / dotnet/efcore

Adding computed column with wrong property type is unfixable (DateTime to DateTime?)

Open
#36,091 0 comments 0 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-migrations customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### Bug description

I added a new database entity that had a Computed Column. Accidentally I added it as "DateTime" while the source is "DateTime?". Fixing this mistakes via migration causes Entity Framework skipping the fact that it's a Computed Columns and tries to generate the change as a real column instead. Fix for me is to comment out the whole thing in the migration since I can't query the table without this change - because it tries to fetch a null value and set it where it can't. Since it's a new table I can just recreate it but it's weird that that is literally is ignoring the fact that the column has been marked as Computed and tries to change the column type as if it isn't.

### Your code

```csharp
// INITIAL ENTITY WITH WRONG 'DATE'

public class Entity
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Date { get; set; }

public DateTime? FullDate { get; set; }
}

entity.Property(e => e.FullDate).ValueGeneratedNever().HasColumnType("datetime").IsRequired(false);
entity.Property(e => e.Date)
.HasComputedColumnSql("(cast(FullDate As Date))");

// NOW DO THIS CHANGE AND CORRECT ABOVE MISTAKE:

public class Entity
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Date { get; set; }

public DateTime? FullDate { get; set; }
}

entity.Property(e => e.FullDate).ValueGeneratedNever().HasColumnType("datetime").IsRequired(false);
entity.Property(e => e.Date)
.HasComputedColumnSql("(cast(FullDate As Date))");

// THIS IS GENERATED IN THE MIGRATION

migrationBuilder.AlterColumn(
name: "Date",
table: "Entities",
type: "date",
nullable: true,
computedColumnSql: "(cast(FullDate As Date))",
oldClrType: typeof(DateTime),
oldType: "datetime2",
oldComputedColumnSql: "(cast(FullDate As Date))");

// THIS IS GENERATED IN SQL SCRIPT:

ALTER TABLE [Entities] ALTER COLUMN [Date] date NULL;

// WHICH CAUSES THIS DURING RUNNING IT

Cannot alter column 'Date' because it is 'COMPUTED'.
```

### Stack traces

```text

```

### Verbose output

```text

```

### EF Core version

8.0.12

### Database provider

_No response_

### Target framework

.NET 8

### Operating system

_No response_

### IDE

17.13.0

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.