简体   繁体   中英

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.

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.

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. There needs to be some way for EF to be able to set the value when loading form the database. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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