3
votes

Entity Framework Core DbSet is not returning any data from database, but the database has many register.

This is the entity

public class Entity : BaseEntity
{
    public int EntityStatusId { get; set; }
    public int AddressId { get; set; }
    public string Name { get; set; }
    public string SocialReason { get; set; }
    public string CNPJ { get; set; }
    public EntityType Type { get; set; }
    public DateTime? CreationDate { get; set; }
    public bool? ReceiptDisabled { get; set; }
    public EntityStatus EntityStatus { get; set; }
    public Address Address { get; set; }
    public List<Company> Companies { get; set; }
    public List<Role> RoleList { get; set; }
}

public abstract class BaseEntity
{
    public int Id { get; set; }
}

Now this is the configuration class.

public class EntityMap : IEntityTypeConfiguration<Entity>
{
    public void Configure(EntityTypeBuilder<Entity> builder)
    {
        builder.ToTable("Entity");
        builder.HasKey(entity => entity.Id);
    
        builder
            .Property(entity => entity.EntityStatusId);
        builder
            .Property(entity => entity.AddressId);
        builder
            .Property(entity => entity.Name);
        builder
            .Property(entity => entity.SocialReason);
        builder
            .Property(entity => entity.CNPJ);
        builder
            .Property(entity => entity.Type)
            .HasConversion(x => (int)x, x => (EntityType)x);
        builder
            .Property(entity => entity.CreationDate);
        builder
            .Property(entity => entity.ReceiptDisabled);

        builder
            .HasOne(entity => entity.EntityStatus);
        builder
            .HasOne(entity => entity.Address);
    
        builder
            .HasMany(entity => entity.RoleList)
            .WithOne(x => x.Entity);
        builder
            .HasMany(entity => entity.Companies)
            .WithOne(x => x.Entity);
    }
}

And the context class.

    public class AucContext : DbContext
    {
        public AucContext(string databaseConfiguration)
        {
            _databaseConfiguration = databaseConfiguration;
        }
        
        private readonly string _databaseConfiguration;

        public DbSet<Campaign> Campaigns { get; set; }
        public DbSet<CampaignProject> CampaignProjects { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<Cart> Carts { get; set; }
        public DbSet<CartItem> CartItems { get; set; }
        public DbSet<Donation> Donations { get; set; }
        public DbSet<DonationRecurrencePeriod> DonationRecurrencePeriods { get; set; }
        public DbSet<Entity> Entities { get; set; }
        public DbSet<Institution> Institutions { get; set; }
        public DbSet<PaymentMethod> PaymentMethods { get; set; }
        public DbSet<Person> People { get; set; }
        public DbSet<Project> Projects { get; set; }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new CampaignMap());
            modelBuilder.ApplyConfiguration(new CampaignProjectMap());
            modelBuilder.ApplyConfiguration(new CompanyMap());
            modelBuilder.ApplyConfiguration(new CartMap());
            modelBuilder.ApplyConfiguration(new CartItemMap());
            modelBuilder.ApplyConfiguration(new DonationMap());
            modelBuilder.ApplyConfiguration(new DonationRecurrencePeriodMap());
            modelBuilder.ApplyConfiguration(new EntityMap());
            modelBuilder.ApplyConfiguration(new InstitutionMap());
            modelBuilder.ApplyConfiguration(new PaymentMethodMap());
            modelBuilder.ApplyConfiguration(new PersonMap());
            modelBuilder.ApplyConfiguration(new ProjectMap());
            modelBuilder.ApplyConfiguration(new UserMap());
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(_databaseConfiguration);
        }
    }

And the query was simple

var entity = context.Entities.Find(3)

enter image description here

this simple query is returning nothing, any ideas for what is happening?

Update

I have updated somethings since yesterday, and now i have updated the question unfortunately still don't work

OBS:. The ConnectionString it's ok, other objects just work fine.

2
Double-check the connection strings in your web.config/app.config and look for any config file in your actual build folder. (if Windows App or Service) Often there is an assumption that the app will be connecting to a particular server/database but with EF configured to create/update a schema, it's gone and created an empty database somewhere else. - Steve Py
The most likely reason is that the application connects to the wrong database. Check your connection string. You can use SQL Server's Profiler or Extended Events to see what commands are sent to the database. You can configure EF Core uses ILogger already to log connection events and the queries it generates. In EF Core 5 you can use LogTo to configure it to write to the Console or any other StreamWriter directly - Panagiotis Kanavos
Check the dbContext seems like initialize issue. Just try var entity = context.Entities.ToList() If doesn't work problem is context not initialized - Yaseer
Can you try add virtual for collection navigation public virtual List<Company> Companies { get; set; } public virtual List<Role> RoleList { get; set; } - Yaseer
@PanagiotisKanavos The OP hadn't included the Map registration code when he first posted the question. He just included the entity and map classes and said he got no data returning. so my original thought was that he hadn't registered the mapping for the entity. He has since updated his question. - Fran

2 Answers

1
votes

First, add Id to your Entity:

public int Id { get; set; }

Then in your DbContext:

1:In your OnModelCreating,add

modelBuilder.ApplyConfiguration(new EntityMap());

2:Add DbSet:

public DbSet<Entity> Entity { get; set; }

Re-migrate and update the database.Your code will work fine.

1
votes

An interesting problem if some entities work but this one doesn't. There are a couple additional things to check/try:

  1. Ensure you have no duplicate mappings. For example, if your Entity has a HasMany.WithOne relationship with another entity, ensure that the mapping for that other entity does not declare a HasOne.WithMany or other relationship back to Entity. This can cause weird behaviour.

  2. Your HasOne relationships are missing WithMany and FK declarations. Given you are using "Id" as a base inherited PK on your entities you should consider explicitly declaring your FK relationships. The WithMany declaration is optional in EFCore, however it is needed to declare the FK if it doesn't follow convention. (and I'm no fan of convention for just deciding not to work)

     builder
         .HasOne(entity => entity.EntityStatus)
         .WIthMany()
         .HasForeignKey(entity => entity.EntityStatusId);
     builder
         .HasOne(entity => entity.Address);
         .WIthMany()
         .HasForeignKey(entity => entity.AddressId);
    

EF should be working out the FK names by convention though. Just keep in mind that EF conventions follow the type name, not property name so for instance something like this:

public User CreatedBy { get; set; }

by convention would be looking for a FK property of UserId rather than CreatedById which can lead to weird behaviour or errors.

On a side note you do not need to declare .Property() for each property in an entity, only for properties that require some special configuration like IdentityColumn, NotMapped (ignore) or specifying a data constraint / length etc. I would also recommend removing the .Property() statement for any FK columns in your entity

This all said, I've tinkered with a test EF Core project setting up duplicate mapping between objects and leaving off WithMany() and FK declarations and I was not able to reproduce your issue. I think there is something very specific to your schema or mapping that is tripping up EF to resolve this "Entity" object. If these changes do not work, take it down to the minimum viable object and remove all related entity mappings, setting them all to NotMapped so-as not to break your code and then try loading your Entity objects. From there re-introduce the relationships one by one until it stops loading them and narrow it down. If you do identify a rogue mapping responsible, do be sure to post an update with details about the culprit because it would probably be useful in case someone else gets tripped up by it.