No such entity with customerId = someid

I am having this error in logs every time a customer is registered after placing new order in Magento 2.3.2

report.CRITICAL: No such entity with customerId = "someid"{"exception":"[object] (Magento\Framework\Exception\NoSuchEntityException(code: 0): No such entity with customerId = "someid" at /mydir/magento/framework/Exception/NoSuchEntityException.php:50)"} [] 

This error wasn’t there and created after update from version 2.3.1 to 2.3.2

Any help please?

DDD and CQRS – Define an entity for Scheduling use case

I have a use case of scheduling a person to some work for some time range. Eg. A service for assigning a person A to work for time range X to Z in location C.

The only constraint it has, is one person cannot work on 2 things at same time. Eg. if person A is assigned to work in time 2019-07-21 to 2010-07-25, then person A cannot be assigned to any other work in that time. Eg. Person A for time range 2019-07-23 to 2019-07-27 should not be possible.

I am trying to make a service for it using domain driven design which would assign a person to some work. The entity I thought would be something like:

class Assignment {     PersonId,     startTime,     endTime,     location } 

Now, I wanted to make sure that if I found a entry in my database for Person A in some time range, then the call to create an entry for Person A in time range that is overlapping with the existing ones should fail.

Since, I am using CQRS model with DDD, so I don’t want to make a query to my database asking for all the assignments for that person. This may not always be recent data because of eventual consistency in CQRS model. I know in my primary key, PersonId would be there but I am not sure how can I use start and end time in it.

Any suggestions what I can do to achieve my goal for this? Is doing DDD and CQRS not a good idea in this? Or there is a better way to model this entity so that I can achieve my goal.

Fastest way to look up an entity with a set of components?

I’m currently trying to implement an ECS system, but I’ve sort of ran into a problem trying to fetch all of my entities that have a specific set of components. I currently have a Dictionary that maps a component name to a list of Guids (entities), so I have no problem fetching a list of entities if I were to query for just one component. But if I were to query entities for more than one component (e.g. all entities that have Render and Transform component), I run into a problem where it’s no longer a constant time lookup.

I could probably loop through the entities to see if they contain that set of component names (they are stored in a dictionary that maps Guid to a list of strings), but I was thinking that there could be a faster way of doing this?

Atualizar campo de saldo, com C# e Entity Framework

Tenho uma dúvida bastante simples, porém não encontrei como resolvê-la no EF.

Preciso reescrever uma SP que hoje roda no SQL, que faz atualização do saldos de contas.


Dessa forma consigo garantir que o saldo será atualizado com o valor atual existente no banco de dados, somando o valor 100.

Como consigo reescrever essa linha, sem a necessidade de buscar previamente o saldo, para atualizar com o novo saldo?

Conseguiram entender minha dúvida?

How do I access a child entity field for reference in an MFTF Test

I need assistance trying to access a field of a required entity inside a parent entity created for a test

Example I am trying to create a configurable product

<createData entity="productAttributeWithTwoOptions" stepKey="createConfigProductAttributes"> 

The entity for that looks like this

<entity name="productAttributeWithTwoOptions" type="ProductAttribute">   <data key="attribute_code" unique="suffix">attribute</data>   <data key="frontend_input">select</data>   ...   <data key="used_for_sort_by">true</data>   <requiredEntity type="FrontendLabel">ProductAttributeFrontendLabel</requiredEntity> </entity> 

In the test how could I access the label field from the FrontendLabel required entity?

<entity name="ProductAttributeFrontendLabel" type="FrontendLabel">   <data key="store_id">0</data>   <data key="label" unique="suffix">attribute</data> </entity> 

I assumed it might be something like this {{createConfigProductAttributes.ProductAttributeFrontendLabel.label}}

Update Entity for Repository Pattern and UOW Pattern C#

In one mock solution, I have created 3 mock projects to implement layered architecture design mainly the – Presentation Layer (Web) – Domain Model Layer – Infrastructure Layer. I haven’t yet to add Application Service Layer (Web API).

For simplicity, I have only two domain model entities: Customer.cs and Category.cs. In my domain model layer, I also put my repository interface (both custom and generic).

In Infrastructure layer, I have the dbcontext, Unit of Work (including its interface) and repository classes (which implement repository interface).

enter image description here

Here is my generic repository interface

public interface IRepositoryGeneric<TEntity> where TEntity : class {     // CRD     void Add(TEntity entity);     void Remove(TEntity entity);     TEntity Get(object Id);     IEnumerable<TEntity> GetAll();      void Save(); } 

Generic Repository class

public class RepositoryGeneric<T> : IRepositoryGeneric<T> where T : class {     protected readonly AppDbContext db;     public RepositoryGeneric(AppDbContext db)     {         this.db = db;     }      public void Add(T entity)     {         db.Set<T>().Add(entity);     }      public T Get(object Id)     {         return db.Set<T>().Find(Id);     }      public IEnumerable<T> GetAll()     {         return db.Set<T>().ToList();     }      public void Remove(T entity)     {         db.Set<T>().Remove(entity);      }      public void Save()     {         db.SaveChanges();     } } 

Unit of Work Interface

public interface IUnitOfWork : IDisposable {     IRepositoryCustomer Customers { get; }     IRepositoryCategory Categories { get; }      int Save(); } 

Unit of Work Class

public class UnitOfWork : IUnitOfWork {     private readonly AppDbContext db;     public UnitOfWork()     {         db = new AppDbContext();     }      private IRepositoryCustomer _Customers;     public IRepositoryCustomer Customers     {         get         {             if (this._Customers == null)             {                 this._Customers = new RepositoryCustomer(db);             }             return this._Customers;         }     }      private IRepositoryCategory _Categories;     public IRepositoryCategory Categories     {         get         {             if (_Categories == null)             {                 _Categories = new RepositoryCategory(db);             }             return _Categories;         }     }      public void Dispose()     {         db.Dispose();     }      public int Save()     {         return db.SaveChanges();     } } 

I learned that I should not have the update method in my generic repository interface. But without update method, I am now stuck at edit method in my presentation MVC web controller. Below, I extracted just the edit action method. The error is in that line in bold.

[HttpPost]     [ValidateAntiForgeryToken]     public ActionResult Edit([Bind(Include = "CategoryID,CategoryName,Description")] Category category)     {         if (ModelState.IsValid)         {             **db.Entry(category).State = EntityState.Modified;**             db.Save();             return RedirectToAction("Index");         }         return View(category);     } 

Lastly, are my classes created in the right layer? Example should IUnitOfWork.cs be in Infrastructure layer?

My whole solution source is available at my github –

Designing an Entity Component System for interfacing with a scripting language

I am currently building an Entity Component System (ECS) in cython in order to speed up operating on large numbers of game objects in python. In the process of building this system, I ran into the following architectural issues that I would appreciate shedding some light upon. I have read through lots of online blog posts describing ECS strategies, but most of these are geared towards C++ and do not describe interfacing such systems with a scripting language like python.

I am defining the parts of my ECS as follows for clarity, since everyone seems to have different terminology/mental frameworks for these concepts:

  • Handle: This is a uint64_t that is subdivided into the following parts:
    • Index (allows for fast access of underlying Comp data given a Comp handle): 32 bits
    • Version (to prevent slot invalidation when adding/removing components): 23 bits
    • Type (aka CompType): 8 bits
    • Free (an internal flag to see if the comp exists): 1 bit
  • Entity: Just a handle, nothing more.
  • Comp (Component): Also just a handle.
  • CompType: A uint8_t (derived from the Handle as above).
  • CompArray: A contiguous, heap-allocated array of data, which can be freely converted to a numpy array for use in python.
  • CompMap: This is a “slotmap” data structure that allows for my components (and entities) to be stored contiguously. Memory is allocated for all of the components of a given type at initialization, and Handles are returned whenever components (or entities) are created. The memory for each component/entity can be retrieved using these handles.
  • Archetype: A set of CompTypes, mapped to a uint16_t for easy access.
  • System: A python class that operates on the Comps belonging to a set of Archetype objects given a passed in world in its update function.
  • EntityManager:
    • Wraps a CompMap object specifically for storing entities.
    • Manages attaching and detaching Comp handles. Does this through bitmasks and storing the Comps (handles) associated with each Entity.
  • CompManager: Stores the sizes, format strings (which detail memory layout), and associated CompMap objects for each CompType. Allows CompTypes to be registered to the system.
  • SystemManager: Stores the System and Archetype objects. Handles calling each system’s update function in the correct order.
  • World: Owns an EntityManager, CompManager, and SystemManager. Has an update function that maps the entities that “belong” to each archetype and iterates over all of the systems’ update functions in a defined order.

Since the component structs are not directly accessible in python outside of numpy arrays, and since I don’t have access to templating magic in python that it typically used for registering components (see the EnTT library’s “registry” as an example of this). As such, I have the following questions regarding how to handle providing access to CompTypes and Components in my ECS in a way that is performant while being usable in python.

  1. Should each “world” in the ECS be able to define its own unique CompTypes and Archetypes?
    • Pros: Allows some flexibility (i.e. there could be a UI specific set of CompTypes for a “UI world” and there would be no need to “waste” CompType int slots for these in the general gameplay world.
    • Cons: Systems can’t reliably operate on multiple worlds if the ints for each of the world’s CompTypes mean different things!
  2. Should the CompTypes and/or Archetypes be strings or ints?
    • Strings:
      • Pros: easy to use from python, uniformly accessible everywhere and clear what each type is based on the characters it stores, likely interned by the python interpreter
      • Cons:
        • Adds a slow, albeit O(1) hashmap access to convert to corresponding CompType int.
          • Although due to interning of string literals, the hash is likely pre-calculated, calling out to a python function is slow.
        • Intertwines use of a python dict for accesses, preventing multithreading due to GIL.
          • Could work around this if I write my own cython hashmap structure as well to replace python’s dict.
    • Ints:
      • Pros: easy to tell which ones are builtin or not based of adding from the last value of the CompTypes enum.
      • Cons: needs to be globally stored so that all systems know what int corresponds to which CompType struct.
  3. How should “built-in” CompTypes and Archetypes from the rest of the game engine be handled?
    • Currently doing this as a global enum inside a cython module.
    • Should these built-in types be auto-registered into every world upon initialization?
  4. Are 256 CompTypes sufficient? Using a uint8_t as part of a larger uint64_t “Handle”.
    • Is there a way to get around having a limit if I am using handles?
    • If I increase the limit to 2^16 instead, then memory usage goes out of control since I would need to store up to 2^16 Comps for each Entity in addition to just my Comp bitmask.

Please let me know if there are any parts that were unclear, and I would be happy to clarify them. Any help would be greatly appreciated.

Conexion desde Core a Base de datos con Entity Framework Core

Hola gente les vengo a comentar un error que me sale y no le encuentro solucion.

Estoy haciendo un curso de CORE y cuando llegue a la parte de usar el entity framework core lo voy entendiendo y todo pero haciendo todo exactamente como lo hizo la persona en el curso me tira errores.

Primero, crea un archivo .cs y en este crea el DbContext y un constructor:

using Microsoft.EntityFrameworkCore; namespace mvc.Models {     public class EscuelaContext : DbContext     {         public DbSet<Escuela> Escuelas { get; set; }         public DbSet<Alumno> Alumnos { get; set; }         public DbSet<Curso> Cursos { get; set; }         public DbSet<Asignatura> Asignaturas { get; set; }         public DbSet<Evaluación> Evaluaciones { get; set; }     }       public EscuelaContext(DbContextOptions<EscuelaContext> options): base(options)     {      } } 

En este paso ya me tira estos errores:

  • A namespace cannot directly contain members such as fields or methods (CS0116) [mvc]

  • Method must have a return type (CS1520) [mvc]

  • ‘object’ does not contain a constructor that takes 1 arguments (CS1729) [mvc]

Luego en el archivo Startup.cs configura el servicio usando un delegado de la siguiente forma:

services.AddDbContext<EscuelaContext>(                 options => options.UseInMemoryDatabase(databaseName = "testDB")                 ); 

y me salta este error: The name ‘databaseName’ does not exist in the current context (CS0103) [mvc]

Usar Attach con claves compuestas en Entity Framework

Estoy intentando actualizar un registro en una tabla y para ello utilizo Entity Framework, para obtener el registro que voy a modificar utilizo Find y la clave, que en este caso es una clave compuesta por dos campos, mi duda es si hay alguna manera de realizar la actualización mediante Attach con claves compuestas, les muestro el código de cómo estoy realizando la actualización en este momento:

using (REPLICAEntities context = new REPLICAEntities())             {                 Lectura lec = context.Lecturas.Find(Fecha, NuTanque);                  //en esta parte actualizo los datos del registro                    context.SaveChanges();             } 

Lo que quiero es usar Attach en vez de Find

De antemano muchas gracias por su ayuda.

“Expiration” of a Domain Entity in Microservice Architecture

I want to implement an expiration functionality for a domain entity. For example:

User queries a Gift Code that should expire somewhere around 30 mins after creation.

I see several approaches to this problem:

  1. Create a Scheduler inside a Service which will run every 30mins in a separate execution thread and expire all Gift Codes. This approach seems not the best one in case of several running instances of a Service. They all will race for the update in database.
  2. Create a Scheduler service which will ping GiftCode service every 30mins. Request will be sent to a single instance of GiftCode service selected by some loadbalancer/discovery server.
  3. Expire Gift Code during its next query/update. This approach is not quite applicable because later some actions (ex. email sending) might be added to be executed after expiration.

My question is whether there might be a better solution to this problem than 3 above.