2011-02-02 4 views
1

私は、次のエンティティモデルを持っている:対応するデータベーステーブルでEntity Frameworkのnull可能なデータベース列にマップする値の型を持つ方法を教えてください。

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にする必要があります。これはどうすればいいですか?

答えて

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; } 
} 

null可能な型は、違いがあり、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

作品!疑問符はトリックでした。ありがとうございました! :-) – user547311

関連する問題