0

我必须使用实体框架和 Linq 查询来进行插入。对于实体类,数据库表上的所有字段都不能为空。我得到了实体类的一些基本字段值,只需要在表上创建一行。但是其余字段可以从实体中为空。请建议我一种防止方法,这样如果我不给这些字段值,实体就不会将其作为空值发送到 db 表,并且可以在表上创建一个新行。

4

1 回答 1

0

NULL/NOT NULL are constraints. When you specify NOT NULL on a column, you are literally telling SQL Server that some value must be provided for that column or the row is invalid. You can't allow nulls on a non-nullable column on a whim as that defeats the entire purpose of the constraint.

So your choices are: 1) you make the column nullable or 2) you provide a default value. At the database level you can run:

ALTER TABLE SomeTable ADD CONSTRAINT DF_SomeColumn DEFAULT [Some Default Value Here] FOR SomeColumn;

Entity Framework does not currently allow specifying default values directly, so you have to modify your table after the fact.

Alternatively, you can simply use a custom getter and setter to provide a default value for your property. This won't put any constraint on the database, though, so it will only work as long as EF is doing the insertion:

private DateTime? createdDate;
public DateTime CreatedDate
{
    get { return createdDate ?? DateTime.UtcNow; }
    set { createdDate = value; }
}
于 2013-06-11T15:30:15.523 回答