简体   繁体   English

实体框架不保存数据

[英]Entity Framework not saving data

I have a model which contains the following property: 我有一个包含以下属性的模型:

public Guid UniqueID
{
    get { return Guid.NewGuid(); }
}

If I examine the object after it is created, I can see that a new guid is correctly created for the UniqueID field. 如果在创建对象后检查该对象,则可以看到已为UniqueID字段正确创建了新的GUID。

However, when I call db.SaveChanges() , I get an error back from Entity Framework stating that it cannot insert NULL into this field despite there being a value present. 但是,当我调用db.SaveChanges() ,我从Entity Framework中收到一条错误消息,指出尽管存在值,但它无法将NULL插入此字段。

Any ideas? 有任何想法吗?

EDIT 编辑

private Guid _uniqueID = Guid.NewGuid();
public Guid UniqueID
{
    get
    {
        if(_uniqueID == null){
            _uniqueID = Guid.NewGuid();
        }
        return _uniqueID;
    }
    set
    {
        _uniqueID = value;
    }
}

EF does not support get-only properties. EF不支持仅获取属性。 There needs to be some way for EF to be able to set the value when loading form the database. 从数据库加载时,EF需要采取某种方式来设置值。 You can use a private setter if you want to make the field immutable: 如果要使该字段不变,则可以使用私有设置器:

private Guid _uniqueID = Guid.NewGuid();
public Guid UniqueID
{
    get
    {
        return _uniqueID;
    }
    private set
    {
        _uniqueID = value;
    }
}

Note that this is slightly different from your edit. 请注意,这与您的编辑略有不同。 I have made the setter private and have taken out the if(_uniqueID == null) since a Guid is a value type and can never be null. 我已经将setter if(_uniqueID == null) private ,并取出了if(_uniqueID == null)因为Guid是一种值类型,并且永远不能为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM