简体   繁体   中英

Getting data from tables with foreign keys C# entity framework

I have this classes in Code First asp.net

public class Account
    {
        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(100)")]
        public string AccountTitle { get; set; }
        public Classification Classification { get; set; }
    }

    public class Classification 
    { 
        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(100)")]
        public string TitleClassification { get; set; }

        public ICollection<Account> Accounts { get; set; }
    }

    public class ClassificationDto
    {
        public int Id { get; set; }
        public string TitleClassification { get; set; }
    }

In my Db Context

public DbSet<Account> Accounts { get; set; }

AccountingManager.FindAll is this

public IQueryable<T> FindAll()
        {
            return context.Set<T>().AsNoTracking().AsQueryable();
        }

I am trying to get just the "Classification" which is just 3 but I am getting the "Account" that is associated with it too with this code:

[HttpGet]
        [Route("get-classification")]
        [Authorize]
        public async Task<IActionResult> GetAccountClassification()
        {
            List<ClassificationDto> classificationList = new List<ClassificationDto>();

            var accountingManager = new AccountingManager(context);

            var list = accountingManager.FindAll();

            classificationList = await list.Select(s => new ClassificationDto
            {
                Id = s.Classification.Id,
                TitleClassification = s.Classification.TitleClassification,
            }).ToListAsync();

            return StatusCode(StatusCodes.Status200OK, classificationList);
        }

This is how it is in my table在此处输入图像描述

If you want to get all rows from Classification table,

add public DbSet<Classification> Classifications { get; set;} public DbSet<Classification> Classifications { get; set;} property to your DbContext class. And then implement similar to FindAll() method:

return context.Classifications.AsNoTracking().ToList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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