实体框架将本地数据添加到数据库列表中 [英] Entity Framework add local data to list from database

查看:69
本文介绍了实体框架将本地数据添加到数据库列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Entity Framework还是很陌生,我正在使用此方法来查询数据库:

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
{
    u.Standort,
    u.Name,
    u.Id
}).ToList();

现在,我的目标是添加数据库中不存在的本地数据.我用这段代码尝试了一下,但是没有用:

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

有人可以帮我吗?谢谢

修改:

我的表类如下:

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

推荐答案

result不是tblStudiosList,而是Anonymous TypeList.因此,如果要将项目添加到result,则应这样做:

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
}).ToList();

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

但是,由于无法投影到映射的实体上,因此需要使用tblStudios实体的所需属性创建像tblStudiosDTO这样的DTO类.

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

这篇关于实体框架将本地数据添加到数据库列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆