Generic Repository in C# Using Entity Framework

后端 未结 2 1525
清歌不尽
清歌不尽 2020-12-11 21:31

I want to retrieve multiple records by giving array of primary key and I have to make generic method of it for all the entities.

private DbSet         


        
相关标签:
2条回答
  • 2020-12-11 21:58

    You can have different names in your application model and your database model. You will have to map your Model Ids to the name in database:

    In your Mapping you will have something similar to this for every entity: this.Property(t => t.Id).HasColumnName("ProductId");

    0 讨论(0)
  • 2020-12-11 22:18

    You can use EF Core provided metadata services like FindEntityType and FindPrimaryKey to get the PK property name. Then you can use it to access the PK value inside LINQ to Entities query using another EF Core provided useful method EF.Property.

    Something like this:

    public virtual List<TEntity> GetByIds(int[] ids)
    {
        var idName = _context.Model.FindEntityType(typeof(TEntity))
            .FindPrimaryKey().Properties.Single().Name;
        return Entities
            .Where(x => ids.Contains(EF.Property<int>(x, idName)))
            .ToList();
    }
    
    0 讨论(0)
提交回复
热议问题