And*_*nho 5 .net c# entity-framework-6 asp.net-core
We were using .Net Core 1 and we migrated to Preview 2 (both with Entity).
Before migration, we used to set a default value for a boolean in Entity Framework like this:
modelBuilder.Entity<Customer>()
.ToTable("Customer")
.Property(a => a.Active)
.HasDefaultValue(true);
Run Code Online (Sandbox Code Playgroud)
After migration, we didn't change anything but now we are getting an error when entity tries to create this table. It looks like it is trying to create a default value as string like "True" and not as a bit, like before.
Does anyone knows what have changed?
ERROR on update-database
The 'bool' property 'Active' on entity type 'Customer' is configured with a database-generated default. This default will always be used when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used when the property value is 'null'.
Script generated:
CREATE TABLE `Customer` (
`Id` int NOT NULL,
`Active` bit NOT NULL DEFAULT 'True'
)
Run Code Online (Sandbox Code Playgroud)
小智 2
我遇到了同样的问题。然而,我自己研究这个问题后发现了一个相当棘手的解决方法。它似乎
如果你将 bool 值设置为可以为空,然后使用 Fluent api 设置默认值,应该没问题。它并不完美,但它有效:
public class Year
{
public int Id { get; set; }
public string label { get; set; }
public int year { get; set; }
public bool? active { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的数据上下文中设置默认值:
modelBuilder.Entity<Year>()
.Property("active")
.HasDefaultValue(true);
Run Code Online (Sandbox Code Playgroud)
当您将新记录插入数据库时,您不需要在对象声明中指定布尔属性。下面,2017 年的默认值为 true。
var newYears = new List<Year>();
newYears.Add(new Year { label = "2019", year = 2019, active = false });
newYears.Add(new Year { label = "2018", year = 2018, active = true });
newYears.Add(new Year { label = "2017", year = 2017});
_context.Years.AddRange(newYears);
_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2682 次 |
| 最近记录: |