Entity Framework Core DbSet is not returning any data from database - entity-framework

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)
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.

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.

An interesting problem if some entities work but this one doesn't. There are a couple additional things to check/try:
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.
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.

Related

Entity Framework Core Many-to-Many Resolve Ambiguity

What is the effective way to resolve ambiguity of many-to-many relationships that point to the same entity either through annotations or fluent configuration? Given models such as:
public class Team
{
public int TeamId { get; set; }
public string Name { get; set; }
// Teams can be owned by multiple users
public List<User> Owners { get; set; }
// Teams can have multiple members
public List<User> Members { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
// User can own zero to many teams
public List<Team> Owners { get; set; }
// User can be a member of zero to many teams
public List<Team> Members { get; set; }
}
Scaffolding results in an error along the lines of "Unable to determine the relationship by navigation "Team.Owners" of type "List".
Is this something that can be effectively resolved by manually creating join entities such as TeamOwner and TeamMember or would EF Core still struggle with ambiguity?
Thanks for any help you can provide.
You have two Navigation properties on each entity, and EF doesn't have a convention to identify which goes with which. So you need to configure the model to explicitly relate the navigation properties. You'll also want to pick a descriptive name for the linking table. EG:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Team>()
.HasMany(t => t.Owners)
.WithMany(o => o.OwnerOf)
.UsingEntity(j => j.ToTable("TeamOwners"));
modelBuilder.Entity<Team>()
.HasMany(t => t.Members)
.WithMany(o => o.MemberOf)
.UsingEntity(j => j.ToTable("TeamMembers"));
base.OnModelCreating(modelBuilder);
}
You can relate the navigation properties with annotations, but can't name the linking table. eg
public class Team
{
public int TeamId { get; set; }
public string Name { get; set; }
[InverseProperty(nameof(User.OwnerOf))]
public List<User> Owners { get; set; }
[InverseProperty(nameof(User.MemberOf))]
public List<User> Members { get; set; }
}

Mapping POCO class which has a (one-to-one) reference to another POCO class with AutoMapper EF Core

My apologies for (perhaps) not using the right terms in the title and this post.
The problem is as follows:
I have a POCO class which has a reference to another table (which is read only). This table has a one-to-one relationship with the other table.
I have set this upo as follow:
public class Commodity
{
public Commodity()
{
}
public long CommodityID { get; set; }
public long CommodityMaterialID { get; set; }
public decimal? SpecficWeight { get; set; }
public OmsCommodityMaterial OmsCommodityMaterial { get; set; }
}
The OmsCommodityMaterial property is the referenced table. This referenced table is also a POCO class which has some other fields, and a porperty back to my own (Commodity) table so I can make a one-to-one relationship with Fluent:
public class OmsCommodityMaterial : OmsBaseClass
{
public OmsCommodityMaterial()
{
}
public long? CommodityMaterialID { get; set; }
public long? CommodityID { get; set; }
public string Name { get; set; }
public long? SortOrder { get; set; }
public Commodity Commodity { get; set; }
}
Fluent (for the one-to-one relation) is set up as follows:
public class MyContext : IdentityDbContext<ApplicationUser>
{
public virtual DbSet<Commodity> Commodity { get; set; }
// Oms classes:
public virtual DbSet<OmsCommodityMaterial> OmsCommodityMaterial { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Commodity>(entity =>
{
entity.Property(e => e.CommodityID)
.HasColumnName("CommodityID")
.ValueGeneratedOnAdd();
entity.Property(e => e.CommodityMaterialID)
.HasColumnName("CommodityMaterialID");
entity.Property(e => e.SpecficWeight)
.HasColumnName("SpecficWeight")
.HasColumnType("decimal(18, 2)");
entity.HasOne(a => a.OmsCommodityMaterial)
.WithOne(b => b.Commodity)
.HasForeignKey<Commodity>(b => b.CommodityMaterialID);
});
}
}
In my endpoint I want to do a GET of all values which return the specific fields of my own table (Commodity) and all the fields of the referenced table (OmsCommodityMaterial).
For this purpose I created a ViewModel (also because else I get a circular reference as I found out in this post: ERR_CONNECTION_RESET returning Async including object child collections) which looks as follow:
public class CommodityViewModel
{
public long CommodityID { get; set; }
public long CommodityMaterialID { get; set; }
public decimal? SpecficWeight { get; set; }
public OmsCommodityMaterial OmsCommodityMaterial { get; set; }
}
For the ViewModels I am using AutoMapper, but I actually have no clue how I can map / return the list of the above ViewModel.
UPDATE
I ended up eliminating the Circular reference error by adding the [JsonIgnore] attribute to the public virtual Commodity Commodity { get; set; } property in the OmsCommodityMaterial POCO class. Now I can get all the needed column values:
return await this.Context.Commodity
.Include(i => i.OmsCommodityMaterial)
.ToListAsync();
Though, I suppose this is not the way to go. There should be a better solution for this by creating a ViewModel that retrieves the Commodity columns and (some) of the referenced OmsCommodityMaterial columns without falling in the Circular Reference error, but how (using AutoMapper)?

Specifying Foreign Key Entity Framework Code First, Fluent Api

I have a question about defining Foreign Key in EF Code First Fluent API.
I have a scenario like this:
Two class Person and Car. In my scenario Car can have assign Person or not (one or zero relationship).
Code:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public Person Person { get; set; }
public int? PPPPP { get; set; }
}
class TestContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Car> Cars { get; set; }
public TestContext(string connectionString) : base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasOptional(x => x.Person)
.WithMany()
.HasForeignKey(x => x.PPPPP)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
In my sample I want to rename foreign key PersonId to PPPPP. In my mapping I say:
modelBuilder.Entity<Car>()
.HasOptional(x => x.Person)
.WithMany()
.HasForeignKey(x => x.PPPPP)
.WillCascadeOnDelete(true);
But my relationship is one to zero and I'm afraid I do mistake using WithMany method, but EF generate database with proper mappings, and everything works well.
Please say if I'm wrong in my Fluent API code or it's good way to do like now is done.
Thanks for help.
I do not see a problem with the use of fluent API here. If you do not want the collection navigational property(ie: Cars) on the Person class you can use the argument less WithMany method.

EF4 CTP5 self-referencing hierarchical entity mapping

Okay, this should be really easy, but I've been tearing my hair out. Here's my POCO (which has to do with machine parts, so a part can be contained within a parent part):
public class Part
{
public int ID { get; set; }
public string Name { get; set; }
public Part ParentPart { get; set; }
}
When the database table is created, the column names are "ID", "Name", and "PartID". How do I change the name of that last column to "ParentPartID"?
Basically, you want to rename the foreign key in an Independent Association and this is the fluent API code that will do it:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Part>()
.HasOptional(p => p.ParentPart)
.WithMany()
.IsIndependent()
.Map(m => m.MapKey(p => p.ID, "ParentPartID"));
}
However, due to a bug in CTP5, this code throw as exception in self referencing associations (which is your association type). The workaround would be to change your association to a Foreign Key Association as follows:
public class Part
{
public int ID { get; set; }
public string Name { get; set; }
public int ParentPartID { get; set; }
[ForeignKey("ParentPartID")]
public Part ParentPart { get; set; }
}

Relationship Mapping in EF4 code-only CTP (when using inheritance?)

I'm producing a simple composite patterned entity model using EF4 w/ the code-first CTP feature:
public abstract partial class CacheEntity
{
[Key]public string Hash { get; set; }
public string Creator { get; set; }
public int EntityType { get; set; }
public string Name { get; set; }
public string Predecessor { get; set; }
public DateTime DateTimeCreated { get; set; }
public virtual ICollection<CacheReference> References { get; set; }
}
public partial class CacheBlob : CacheEntity
{
public byte[] Content { get; set; }
}
public partial class CacheCollection : CacheEntity
{
public virtual ICollection<CacheEntity> Children { get; set; }
}
public class CacheReference
{
public string Hash { get; set; }
[Key]public string Reference { get; set; }
public virtual CacheEntity Entity { get; set; }
}
public class CacheEntities : DbContext
{
public DbSet<CacheEntity> Entities { get; set; }
public DbSet<CacheReference> References { get; set; }
}
Before I split out the primitive/collection derived classes it all worked nicely, but now I get this:
Unable to determine the principal end of the 'Cache.DataAccess.CacheEntity_References'
relationship. Multiple added entities may have the same primary key.
I figured that it may have been getting confused, so I thought I'd spell it out explicitly using the fluent interface, rather than the DataAnnotation attributes. Here's what I think defines the relationship properly:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CacheEntity>().HasKey(ce => ce.Hash);
modelBuilder.Entity<CacheEntity>().HasOptional(ce => ce.References).WithMany();
modelBuilder.Entity<CacheReference>().HasKey(ce => ce.Reference);
modelBuilder.Entity<CacheReference>().HasRequired(cr => cr.Entity).WithOptional();
}
But I must be wrong, because now I get this:
Entities in 'CacheEntities.CacheReferenceSet' participate in the
'CacheReference_Entity' relationship. 0 related 'Entity' were found. 1 'Entity' is expected.
Various other ways of using the fluent API yield different errors, but nothing succeeds, so I am beginning to wonder whether these need to be done differently when I am using inheritance.
Any clues, links, ideas, guidance would be very welcome.
using the MapHierarchy works for me:
protected override void OnModelCreating(ModelBuilder builder){
builder.Entity<CacheBlob>().HasKey(b=> b.Hash).MapHierarchy();
}
As an example.
Further reference : http://blogs.msdn.com/b/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx