Anokrize Anokrize - 1 year ago 75
SQL Question

Entity Framework add local data to list from database

I am pretty new to Entity Framework and I am using this method in order to query through my database:

var _context = new StudioEntities();
var results = _context.tblStudios.Select(u => new

Now my goal is to add local data as well which isn't present in the database. I tried it with this code but it didn't work:

results.Add(new tblStudio { Id = 0, Name = "Gesamt" });

Can someone help me with this? Thanks


My table class looks like this:

public partial class tblStudio
public int Id { get; set; }
public string Name { get; set; }
public string Standort { get; set; }
public Nullable<int> Plz { get; set; }

Answer Source

The result is not a List of tblStudios, it is a List of Anonymous Type. So if you want to add an item to the result you should do like this:

var results = _context.tblStudios.Select(u => new tblStudiosDTO()
    Standort = u.Standort,
    Name = u.Name,
    Id = u.Id

results.Add(new tblStudio () { Id = "0", Name = "Gesamt" });

But because you cannot project onto a mapped entity then you need to create a DTO class like tblStudiosDTO with needed properties from the tblStudios entity.

public class tblStudiosDTO 
    public string Standort { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download