dotnet / dotnet/EntityFramework.Docs

HasDefaultValueSql is overriding my actual supplied value it seems

Open
#3,852 14 comments 0 reactions 1 assignee Assigned to @AndriySvyryd View on GitHub
area-change-tracking area-model-building
Dominant language
Mermaid
Stars
1.7k
Forks
2k
Avg merge
7d 23h
Merged PRs (30d)
16

Description

HasDefaultValueSql is doing something I can't explain

I have a simple class

```
public partial class ApplicantAddress
{
public ApplicantAddress()
{
Applicant = new HashSet();
}

public int AddressId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string AddressTowncity { get; set; }
public string AddressPostCode { get; set; }
public string AddressCountry { get; set; }
public string AddressProviceOrState { get; set; }
public bool AddressTrusted { get; set; }
public virtual ICollection Applicant { get; set; }
}
```

The AddressTrusted has a SQL default of TRUE

```
entity.Property(e => e.AddressTrusted)
.HasColumnName("address_trusted")
.HasDefaultValueSql("((1))");
```

It has a constraint on the database

```
ALTER TABLE [dbo].[applicant_address] ADD CONSTRAINT [df_address_trusted] DEFAULT ((1)) FOR [address_trusted]
GO
```

In my code I set the value

```
ApplicantAddress NewAddress = new ApplicantAddress
{
AddressLine1 = NewApplicant.Address.Line1?.Trim(),
AddressLine2 = NewApplicant.Address.Line2?.Trim(),
AddressLine3 = NewApplicant.Address.Line3?.Trim(),
AddressTowncity = NewApplicant.Address.TownCity?.Trim(),
AddressPostCode = NewApplicant.Address.PostalCode?.Trim(),
AddressCountry = NewApplicant.Address.Country?.Trim(),
AddressProviceOrState = NewApplicant.Address.ProvinceState?.Trim(),
AddressTrusted = false
};
```

But the value is ALWAYS being written as TRUE to the table

I put tracing on and I saw

```
INSERT INTO [applicant_address] ([address_country], [address_line_1], [address_line_2], [address_line_3], [address_post_code], [address_provice_or_state], [address_towncity])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6);
SELECT [address_id], [address_trusted]
FROM [applicant_address]
WHERE @@ROWCOUNT = 1 AND [address_id] = scope_identity();
```

Why is it not being INSERTED? It selects the value back for some reason.

Rather than the default being used if I don't provide a value, it seems the default is being used to override my value!

### Include provider and version information

EF Core version: 6.0.3
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: 6.0.3
Operating system: Windows
IDE: (e.g. Visual Studio 2022 17.1.5

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.