简体   繁体   中英

.NET C# I want to get the IDs (1/multiple) from a data if it much the ID of another table

Models:

namespace practise_API.Model
{
    public class SourceAttributes
    {
        [Key]
        public int SourceEntityId { get; set; }

        public int ATiD { get; set; }
        public string Name { get; set; }
        public string Datatype { get; set; }
    }

    public class OtherData
    {
        public int ID { get; set; }
        public string Ename { get; set; }
        public string Type { get; set; }
        public string Source { get; set; }
        public string Frequency { get; set; }
    }
}

IRepository interface:

namespace API.Repository
{
    public interface ISourceRepository
    {
        IEnumerable<SourceEntities> GetSourceEntities();
        IEnumerable<SourceAttributes> GetSourceAttributes(int id);

        ........
        void Save();
    }
}

Repository implementation:

public class SourceRepository : ISourceRepository
{
    private readonly MapperDbContext _dbContext;

    public SourceRepository(MapperDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IEnumerable<SourceAttributes> GetSourceAttributes()
    {
        return _dbContext.SourceAttributes
                         .Where(i => i.SourceEntityId == OtherData.ID)
                         .ToList();
    }
}

I want to get all the SourceAttributes.SourceentityIds that match that one ID from OtherData . The way I thought about it was to use where() System.Linq but I can't get the OtherData.ID.

Also this is going to be called later in my Get() of my controller.

The ISourceRepository.GetSourceAttributes has an id parameter, but the implementation is missing it resulting surely in a compiler error. Modify it:

public IEnumerable<SourceAttributes> GetSourceAttributes(int otherDataId)
{
   return _dbContext.SourceAttributes
      .Where(i => i.SourceEntityId == otherDataId)
      .ToList();
}

To get the ids you want:

var ids = sourceRepository
            .GetSourceAttributes(myOtherDataInstance.ID)
            .Select(i => i.ID)
            .ToArray();   // or leave it as IEnumerable as you wish

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