DaRoGa
DaRoGa

Reputation: 2404

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

Upvotes: 0

Views: 400

Answers (1)

D Stanley
D Stanley

Reputation: 152556

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.

Upvotes: 1

Related Questions