简体   繁体   English

.Net如何使用数据库中不存在的字段加载ViewModel?

[英].Net How to load a ViewModel with fields that don't exist in the database?

How can I query the DB to return a list of items that have fields in addition to what the entity models describe> 我如何查询数据库以返回除了实体模型描述的内容以外还具有字段的项目列表>

Say I have entity models called Owners and Pets: 假设我有一个称为“所有者和宠物”的实体模型:

public class Owner
{
    public int OwnerID{ get; set; }

    public virtual IEnumerable<Pets> Pets{ get; set; }
}

public class Pet
{
    public int PetID{ get; set; }
    public string PetName{ get; set; }

    public int OwnerID{ get; set; }
    public Owner Owner{ get; set; }
}

If I got a list of owners like this: 如果我有这样的所有者列表:

dbContext.Set<Owner>().ToList()

Each object in that list would be an Owner with OwnerID and a list of their pets. 该列表中的每个对象都是具有OwnerID及其宠物列表的Owner。

But, what if I wanted to include an extra field for each of those Owners, like "HasPets", and have a list of viewmodels that accepts that. 但是,如果我想为每个所有者包括一个额外的字段,例如“ HasPets”,并有一个接受该视图的视图模型列表,该怎么办?

public class OwnerViewModel
{
    public int OwnerID{ get; set; }
    public bool HasPets{ get; set; }
}

List<OwnerViewModel> OwnerViewModels = ....(get list with added field)

I have no idea how to query the DB to include a new calculated field... 我不知道如何查询数据库以包括新的计算字段...

(I realize I could simply do a count on Owner.Pets, but I just wanted to keep the example simple) (我意识到我可以简单地依靠Owner.Pets,但我只是想保持示例简单)

@Kamyar is pretty much right, the only thing I would do differently is use .Any() as opposed to .Count() > 0 @Kamyar是非常正确的,我会做出不同的唯一事情就是用.Any()而不是.Count() > 0

context.Owners
            .Select(o => new OwnerViewModel
                                {
                                    OwnerID = o.OwnerID,
                                    HasPets = o.Pets.Any().
                                    ...
                                    ...
                                });

Something like 就像是

context.Owners.Select(o => new OwnerViewModel() 
                           {Owner = o, HasPets = o.Pets.Any()});  

And define your viewmodel like: 并像这样定义您的viewmodel:

public class OwnerViewModel
{
    public Owner Owner{ get; set; }
    public bool HasPets{ get; set; }
}

Or you can load all the pets client-side, and check them there (of course not recommended for the overload): 或者,您可以在客户端加载所有宠物,并在此处检查它们(当然不建议超载):

public class OwnerViewModel
{
    public Owner Owner{ get; set; }
    public bool HasPets{ get { return this.Owner.Pets.Any(); } }
}  
var ownervms = new List<OwnerViewModel>();
foreach (var owner in context.Owners)
{
    ownervms.Add(new OwnerViewModel() {Owner= owner});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM