具有ApplicationUser属性的实体,当我在服务中使用它时,该属性为null

时间:2019-01-07 20:58:49

标签: c# asp.net-core

我有一个名为CarOwner的实体。每个车主都有一个属性ServiceAppUser AutoService。当我添加新的CarOwner时,我在CarOwnerService中使用Create方法

在SSMS中,一切看起来都很好。

但是当我点击Details方法并尝试通过GetById获取CarOwner时,在CarOwnerService中我发现了AutoService == null和Cars == null的CarOwner

public class CarOwner : BaseModel<int>
{
    public CarOwner()
    {
        this.Cars = new HashSet<Car>();
    }

    public string Name { get; set; }

    public string Bulstat { get; set; }

    public string Address { get; set; }

    public string City { get; set; }

    public string MRP { get; set; }

    public string Email { get; set; }

    public string Telephone { get; set; }

    public virtual ICollection<Car> Cars { get; set; }

    public decimal Obligation { get; set; }

    public string ServiceAppUserId { get; set; }

    public virtual ServiceAppUser AutoService { get; set; }
}


public class CarOwnerService : ICarOwnerService
{
    private IRepository<CarOwner> carOwnerRepository;
    private IMapper mapper;

    public CarOwnerService(IRepository<CarOwner> carOwnerRepository, IMapper mapper)
    {
        this.carOwnerRepository = carOwnerRepository;
        this.mapper = mapper;
    }

    public async Task<int> Create(CarOwnerCreateViewModel model, ServiceAppUser user)
    {

        var carOwner = mapper.Map<CarOwner>(model);
        carOwner.AutoService = user;

        await this.carOwnerRepository.AddAsync(carOwner);
        await this.carOwnerRepository.SaveChangesAsync();

        var id = carOwner.Id;

        return id;
    }



    public CarOwner GetById(int id)
    {
        var allCarOwners = this.carOwnerRepository.All();
        var carOwner = allCarOwners.FirstOrDefault(o => o.Id == id);

        return carOwner;
    }

    public IEnumerable<CarOwnerViewModel> GetAll()
    {

        var all = this.carOwnerRepository.All().ToList().Select(co => mapper.Map<CarOwnerViewModel>(co));

        return all;
    }
}

2 个答案:

答案 0 :(得分:0)

我不确定,但是听起来您可能正在使用Entity Framework Core或另一个ORM,因为您提到了SSMS。

很难看到IRepository的实现,但是很难确定,但是通常来说,您描述的问题是因为您没有告诉ORM包括对象图的其他部分。

例如

dbContext.CarOwners
         .Include(c => c.Cars)
         .Include(c => c.AutoService)
         .Select(c => c);

将返回您所有的对象,并填充CarsAutoService

警告,请注意仅Include确切地满足任何通话需求,否则将导致加载过多数据并降低应用程序速度。

答案 1 :(得分:0)

这是我的IRepository,是的,我正在使用EF Core

window.onload(function() {
 var itemStyle = localStorage.getItem('a2');
 var as = document.getElementById("a2");
 as.classList.add(itemStyle);
}

这是我对IRepository的实现:

public interface IRepository<TEntity>
 where TEntity : class
{
    IQueryable<TEntity> All();

    bool Contains(TEntity entity);

    Task AddAsync(TEntity entity);

    void Delete(TEntity entity);

    Task<int> SaveChangesAsync();
}