gpt4 book ai didi

c# - 如何在 Entity Framework 中具有映射到可为空的数据库列的值类型?

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:51 24 4
gpt4 key购买 nike

我有以下实体模型:

public class Todo  
{
[Required]
public int ID { get; set; }
public int OrderId { get; set; } //Not required
public string Description { get; set; }
public bool Finished { get; set; }
public DateTime CreationDate { get; set; }
public int Priority { get; set; } //Not required
public string CreatedBy { get; set; }
public bool Deleted { get; set; }
}


在相应的数据库表中,所有字段都创建为“ not null”。我想允许某些字段为空。我该怎么做呢?

最佳答案

在数据库方面,您将必须更改想要为可选字段的字段,以便它们可以为空。 ALTER TABLE语句可以解决问题。

ALTER TABLE Todo
ALTER COLUMN OrderId int NULL

ALTER TABLE Todo
ALTER COLUMN Priority int NULL


在应用程序方面,您需要使用 nullable types。尝试这个:

public class Todo
{
[Required]
public int ID { get; set; }
public int? OrderId { get; set; } //Not required
public string Description { get; set; }
public bool Finished { get; set; }
public DateTime CreationDate { get; set; }
public int? Priority { get; set; } //Not required
public string CreatedBy { get; set; }
public bool Deleted { get; set; }
}


可为空的类型是常规值类型的变体,不同之处在于它可以为空。在代码中,您可以使用 HasValue属性测试是否为空:

int? foo= 42;
Console.WriteLine(foo.HasValue); // prints True
Console.WriteLine(foo.Value); // prints 42
int? bar = null;
Console.WriteLine(bar.HasValue); // prints False
Console.WriteLine(bar.Value); // throws InvalidOperationException


该类型的所有运算符都将被解除,这意味着您仍然可以使用它们进行算术运算:

int? foo = 23;
int? bar = 17;
int? foobar = foo + bar;
Console.WriteLine(foobar); // Prints 40
int? baz = null;
int? foobaz = foo + baz + bar; // If any of them is null, the result will be null.
Console.WriteLine(foobaz); // Prints null

关于c# - 如何在 Entity Framework 中具有映射到可为空的数据库列的值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4873440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com