use*_*311 1 c# entity-framework nullable
我有以下实体模型:
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; }
}
Run Code Online (Sandbox Code Playgroud)
在相应的数据库表中,所有字段都创建为"not null".我想允许一些字段为空.我该怎么做呢?
在数据库端,您必须更改要作为可选字段,以便它们可以为null.ALTER TABLE语句可以解决这个问题.
ALTER TABLE Todo
ALTER COLUMN OrderId int NULL
ALTER TABLE Todo
ALTER COLUMN Priority int NULL
Run Code Online (Sandbox Code Playgroud)
在应用程序方面,您需要使用可空类型.试试这个:
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; }
}
Run Code Online (Sandbox Code Playgroud)
可空类型是常规值类型的变体,区别在于它可以为null.在您的代码中,您可以使用HasValue属性测试null :
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
Run Code Online (Sandbox Code Playgroud)
该类型的所有运算符都被提升,这意味着您仍然可以使用它们进行算术运算:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6163 次 |
| 最近记录: |