实体框架将本地数据添加到数据库列表中

Tom*_*adi 2 c# sql linq entity-framework

我是Entity Framework的新手,我使用这个方法来查询我的数据库:

var _context = new StudioEntities();
var results = _context.tblStudios.Select(u => new
{
    u.Standort,
    u.Name,
    u.Id
}).ToList();
Run Code Online (Sandbox Code Playgroud)

现在我的目标是添加本地数据,这些数据在数据库中不存在.我尝试使用此代码,但它不起作用:

results.Add(new tblStudio { Id = 0, Name = "Gesamt" });
Run Code Online (Sandbox Code Playgroud)

有人可以帮我弄这个吗?谢谢

编辑:

我的表类看起来像这样:

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; }
}
Run Code Online (Sandbox Code Playgroud)

Sal*_*ari 5

result不是ListtblStudios,它是ListAnonymous Type.因此,如果您想要添加项目,result您应该这样做:

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

results.Add(new tblStudiosDTO() { Id = "0", Name = "Gesamt" });
Run Code Online (Sandbox Code Playgroud)

但是因为您无法投影到映射的实体,所以您需要创建一个DTO类,其中包含tblStudiosDTO来自tblStudios实体的所需属性.

public class tblStudiosDTO 
{
    public string Standort { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)