2011-02-02 2 views
1

나는 다음과 같은 엔티티 모델이 있습니다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; } 
} 

모든 필드는 "null가 아닌"로 생성 된 해당 데이터베이스 테이블에 있습니다. 일부 필드가 null이되도록 허용하려고합니다. 어떻게해야합니까?

답변

9

데이터베이스 측에서는 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; } 
} 

nullable 유형은 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 

모든 사업자가 해제되어, 당신은 여전히 ​​그들과 함께 연산을 할 수 있다는 것을 의미한다 : 마법처럼

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 
+0

작품! questionmark 트릭을했다. 고맙습니다! :-) – user547311

관련 문제