Nikita
Nikita

Reputation: 1082

Entinty Framework saving context with null fields mvc5

This is object Image

public int Id { get; }           //primary key
public string Path { get; set; } //not null
public string Name { get; set; } //not null
public string Url { get; set; }  //allows null
public string SecureUrl { get; set; } //allows null

EFDbImageRepository

public void UploadToCloud(Image image)
{
    System.Diagnostics.Debug.WriteLine(image.Id);
    if(image.Id == 0)
    {
        context.Images.Add(image);
    }else
    {
        Image dbEntry = context.Images.Find(image.Id);
    }
    context.SaveChanges();
}

In controller in the UploadImage action

 ...   
 Image image = new Image();
 image.init(path, "defaultName1", "type");
 imageRepository.UploadToCloud(image);
 ...

At moment UploadToCloud I have en exception: 'System.Data.Entity.ModelConfiguration.ModelValidationException' in EntityFramework.dll

It seems that there is a problem with data, that I try to save, but I don't understand what is wrong. At this moment I initialize only 2 fields Path and Name. Id should be set automatically, Url and SecureUrl allows null, so all should be good.

How to save object to database?

Upvotes: 1

Views: 44

Answers (1)

Dabblernl
Dabblernl

Reputation: 16121

You made the Id field readonly. Entity frameworke ignores readonly properties, so you have now created an entity without a primary key. You have at least to add private set, but why no ordinary (public) {get;set;}?.

Upvotes: 1

Related Questions