EF Core, return entry or create and return

.net-core entity-framework-core

Question

I have a .net framework 4.5 project I am trying to convert to asp .net core 3.1. I am having trouble figuring out a simple way to convert the following code:

var entry = db.mytable.FirstOrDefault(s => s.Name == "myname");
if (entry == null)
{
    entry = db.mytable.Add(new mytable()
    {
        Name = "myname"
    });
    db.SaveChanges();
}
int myNewID = entry.ID;

After converting to .net core, this code throws the following error:

Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<project.model.mytable>' to 'project.model.mytable' 

Does anyone know a good way to address this?

1
1
2/28/2020 6:02:33 PM

Accepted Answer

var entry = db.mytable.FirstOrDefault(s => s.ID == id);
if (entry == null)
{
    entry = new mytable()
    {
        ID = id
    });

 db.mytable.Add(entry);

    db.SaveChanges();
}
int id = entry.id;

As it was, entry = db.mytable.Add(new mytable()... returns an EntityEntry which provides tracking information, not the actual entity.

2
2/28/2020 6:19:00 PM

Popular Answer

To add to @JMP's answer:

See: DbSet.Add

In your code:

entry = db.mytable.Add(new mytable()
{
    ID = id
});

You assign the return of Add, which is EntityEntry<TEntity>, whereas earlier in your code, the "entry" variable is declared as TEntity. This is why you get the message:

Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry' to 'project.model.mytable'



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow