Additional entity ID for networking instead of the common EID?

A UUID occupies 128 bits.

Your own ID can be as small as ceil(log_2(n)) bits; Where n is the number of entities between which you want to distinguish.

Obtaining the entity from the UUID requires a hashmap. With a clever ID system, you can simply index an array instead, which is a bit faster.

You can also typically embed some type information in the ID by assigning ranges to each type. This way you can avoid a downcast / type check in the network code because you can have separate containers for each type.

User Behavior – Ability to hide the identity of the verifier from the entity being audited

background

Suppose I have a platform similar to Yelp, but it is just for ONE small town (80,000 inhabitants) and contains only a list of workers, not companies.

In such a small town, most people are closely linked to the social network. This means that it is relatively easy for one person to trip over another.


The problem

If Mary hires John for a job but Mary does not like the end result of John's work and leaves him a bad rating on the platform, How can you give Mary the opportunity to hide her identity in order to avoid an unpleasant situation if she stumbles over John? Not only unpleasant situations, but also harassment by John, what is a possibility, am I right?

Why just hide her name does not work:

If John had only one client (Mary) in a long period of time and then received an anonymous bad rating shortly after the job, he would do the math in his head and know that the author of the rating must be Mary.


My solution

I thought about just publishing anonymous reviews of groups of 2 or more so John would not know who the person behind the review was.


The questions

Feel free to answer one (or all) of these questions.

  • Have you had a problem like this? How did you solve it?
  • Can you tell me how to improve my solution?
  • Is this an old problem that I am not aware of? If so, is there a better solution?

entity – Drupal 8.7 Change the field type for the custom entity (from integer to decimal) with existing data

Yes, I have seen previous answers, but I am looking for a new answer:

I do not know the Drupal 8 memory system well enough, so I'm looking for insights too.

I looked at a lot of documentation, including:

What caught my attention is this: "Starting with Drupal 8.7.0, the entity system provides a new update API for converting the schema of a content entity type from (not) revisable / (untranslatable) to auditable / translatable. This works even if there is already data for the entity type whose schema is being changed.. "

This was an indication of how to change a field type with existing data without having to write a lot of code.

So I've tried to change a field type of my custom entity that already contains data (~ 10000 lines).

function mymodule_post_update_0011_field_conversion(array $sandbox) {
    $definition_update_manager = Drupal::entityDefinitionUpdateManager();
    $last_installed_schema_repository = Drupal::service('entity.last_installed_schema.repository');

    $entity_type = $definition_update_manager->getEntityType('my_entity_id');
    $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('my_entity_id');

    // Update field already existing in $field_storage_definitions
   // I also tried to create a new field, with the same outcome.
    $field_storage_definitions('order_vat') = BaseFieldDefinition::create('decimal')
      ->setLabel(t('Order VAT Rate'))
      ->setDescription(t('Order VAT Rate.'))
      ->setSettings(('precision' => 5, 'scale' => 2));

    Drupal::entityDefinitionUpdateManager()
      ->updateFieldableEntityType($entity_type, $field_storage_definitions,$sandbox);
  }

What ends with one DrupalCoreEntityEntityStorageException : Unsupported entity type

I tried using the same function to insert a new field into the entity, with the same error as the result.

Something is wrong with my attempt, and this can only be done manually in one post_update_hookto create a new field with the appropriate type, copy all values ​​from old to new, clear the old one and delete the old field?

This seems to be a lot of a simple operation that I could do in my case with a fairly simple SQL statement.

Last precision, this is a custom entity created from code only (ContentEntityBase), without revision (for now), which contents are manipulated only programmatically.

Should an ASP.NET Web API application use entity frameowrk in the API controllers?

I'm a bit confused about the best practices when working with Entity Framework and ASP.NET Web API.

I'm working on a project that includes an iOS / Android app and an API that the app communicates with.

The project is divided as follows:

  • Project.Core (This project contains all database accesses such as dbContext, entity models, services that control the logic of the system, and the services return only mapped models.) The entity models are never exposed in this project.)

  • Project.Models (This project contains all associated models used by the app and the API.)

  • Project.Api (Contains all API controllers, actions, and authorization logics.) This project uses the Project.Core services to perform the desired action and only works with the associated models.)

Now my question is:

  1. Is it a bad practice not to use the Entity Framework models and DbContext directly in the API project?

  2. Is it a bad practice to hide the Entity Framework models and DbContext from all other projects except Project.Core?

My idea was to isolate the entire database logic in a separate project.

Entity Framework Property with GET (GetterOnly) with IQueryable linq C #

I do not know exactly what it means when it depicts the return to the method as follows, but I will try to explain, for example, that I have the following class:

public class Venda(){
   public decimal Valor {get;set;}
   public decimal Desconto {get;set;}
   public decimal ValorLiquido => Valor - Descontos;
}

I use EntityFramework and this class would be a database model. I need to create a sales report and in this report I use the NetValue property and the problem is the following query:

var vendas = ctx.Vendas;

This gives me back a good query so far, but when I try to use the NetValue property, I get the following message:

The specified type member & # 39; NetValue & # 39; is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

If I give ToList() It works and I can access the property, but it's a report with more than 50,000 items, and in the real class, there are about 10 more GetterOnly properties for it, so it's not practical to use them ToList().
The question is:
In this case, is there any way to access this property without specifying ToList () in an IQueryAble list?

Entity Framework Property with GET in IQueryable C #

I do not know exactly what it means when it depicts the return to the method as follows, but I will try to explain, for example, that I have the following class:

public class Venda(){
   public decimal Valor {get;set;}
   public decimal Desconto {get;set;}
   public decimal ValorLiquido => Valor - Descontos;
}

I use EntityFramework and this class would be a database model. I need to create a sales report and in this report I use the NetValue property and the problem is the following query:

var vendas = ctx.Vendas;

This gives me back a good query so far, but when I try to use the NetValue property, I get the following message:

The specified type member & # 39; NetValue & # 39; is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

If I give ToList() It works and I can access the property, but it's a report with more than 50,000 items, and in the real class, there are about 10 more GetterOnly properties for it, so it's not practical to use them ToList().
The question is:
In this case, is there any way to access this property without specifying ToList () in an IQueryAble list?

entity – How can I cause entityQuery (& # 39; commerce_order & # 39;) to return completed orders?

Under Drupal Commerce 8.x-2.13 I find that the query

Drupal::entityQuery('commerce_order') 

Without conditions, ONLY incomplete orders are returned (if they are called in the context of an API endpoint) – and if I use parameters without incomplete orders, such as:

$query->condition('state', 'completed');

there is nothing back. How can an entityQuery be run to retrieve data about completed orders?

mysql – How do I model an entity type that can have different sets of attributes?

According to your description of the considered business environment there is one Supertype subtype Structure that includes items – the supertype – and each one of his Categoriesi.e. automobile. boat and level (along with two others that were not disclosed) – the subtypes -.

In the following, I will discuss in detail the method by which I would manage such a scenario.

To delineate the relevant conceptual Scheme, some of the most important business rules previously determined (restriction of the analysis to the three disclosed Categories just to keep things as short as possible) can be formulated as follows:

  • ON user has zero-one-or-many items
  • On items belongs exactly one user at a certain time
  • On items can be owned by one too many user at certain times
  • On items is classified after exactly one category
  • On items is at all times,
    • either one automobile
    • or a boat
    • or a level

Figure 1 shows an IDEF1X1 Chart I created to group the previous phrases together with other business rules that seem relevant:

Figure 1 - Element and Categories supertype subtype structure

Super Type

On the one hand, items, the supertype, presents the properties or attributes that are common to all Categoriesi.e.

  • Category code -The ALIEN KEY (FK) referred to Category.CategoryCode and acts as a subtype discriminatori.e. it indicates the exact category of subtype with which a given items must be connected -,
  • ownerID – Awarded as FK, which suggests User.UserIDbut I assigned him a role name2 to more accurately reflect his particular implications –
  • foo.
  • bar.
  • Baz and
  • CreatedDateTime,

subtypes

On the other hand the characteristics this affects every single one categoryi.e.

  • qux and Corge;
  • Grault. Garply and plugh;
  • Xyzzy. Thud. Wibble and Flob;

are displayed in the corresponding subtype field.

identifiers

Then that is Item.ItemId PRIMARY KEY (PK) has been migrated3 to the subtypes with different role names, d. H.

  • CarId.
  • BoatId and
  • PlaneId,

Mutually exclusive associations

As shown, there is an association or relationship of cardinality one to one (1: 1) between (a) each supertype occurrence and (b) its complementary subtype instance.

The exclusive subtype The symbol shows the fact that the subtypes are mutually exclusive, d. H items The occurrence can only be supplemented by a single instance of the subtype: one of the two automobileor one levelor one boat (Never at two or more).

. I used classic wildcard names to qualify some of the entity type properties because their actual names were not specified in the question.

To discuss the logical design of an Expositories, I have derived the following SQL DDL statements based on the IDEF1X chart displayed and described above:

-- You should determine which are the most fitting 
-- data types and sizes for all your table columns 
-- depending on your business context characteristics.

-- Also, you should make accurate tests to define the 
-- most convenient INDEX strategies based on the exact 
-- data manipulation tendencies of your business context.

-- As one would expect, you are free to utilize 
-- your preferred (or required) naming conventions. 

CREATE TABLE UserProfile (
    UserId          INT      NOT NULL,
    FirstName       CHAR(30) NOT NULL,
    LastName        CHAR(30) NOT NULL,
    BirthDate       DATE     NOT NULL,
    GenderCode      CHAR(3)  NOT NULL,
    Username        CHAR(20) NOT NULL,
    CreatedDateTime DATETIME NOT NULL,
    --
    CONSTRAINT UserProfile_PK  PRIMARY KEY (UserId),
    CONSTRAINT UserProfile_AK1 UNIQUE ( -- Composite ALTERNATE KEY.
        FirstName,
        LastName,
        GenderCode,
        BirthDate
    ),
    CONSTRAINT UserProfile_AK2 UNIQUE (Username) -- ALTERNATE KEY.
);

CREATE TABLE Category (
    CategoryCode     CHAR(1)  NOT NULL, -- Meant to contain meaningful, short and stable values, e.g.; 'C' for 'Car'; 'B' for 'Boat'; 'P' for 'Plane'.
    Name             CHAR(30) NOT NULL,
    --
    CONSTRAINT Category_PK PRIMARY KEY (CategoryCode),
    CONSTRAINT Category_AK UNIQUE      (Name) -- ALTERNATE KEY.
);

CREATE TABLE Item ( -- Stands for the supertype.
    ItemId           INT      NOT NULL,
    OwnerId          INT      NOT NULL,
    CategoryCode     CHAR(1)  NOT NULL, -- Denotes the subtype discriminator.
    Foo              CHAR(30) NOT NULL,
    Bar              CHAR(30) NOT NULL,
    Baz              CHAR(30) NOT NULL,  
    CreatedDateTime  DATETIME NOT NULL,
    --
    CONSTRAINT Item_PK             PRIMARY KEY (ItemId),
    CONSTRAINT Item_to_Category_FK FOREIGN KEY (CategoryCode)
        REFERENCES Category    (CategoryCode),
    CONSTRAINT Item_to_User_FK     FOREIGN KEY (OwnerId)
        REFERENCES UserProfile (UserId)  
);

CREATE TABLE Car ( -- Represents one of the subtypes.
    CarId INT      NOT NULL, -- Must be constrained as (a) the PRIMARY KEY and (b) a FOREIGN KEY.
    Qux   CHAR(30) NOT NULL,
    Corge CHAR(30) NOT NULL,   
    --
    CONSTRAINT Car_PK         PRIMARY KEY (CarId),
    CONSTRAINT Car_to_Item_FK FOREIGN KEY (CarId)
        REFERENCES Item (ItemId)  
);

CREATE TABLE Boat ( -- Stands for one of the subtypes.
    BoatId INT      NOT NULL, -- Must be constrained as (a) the PRIMARY KEY and (b) a FOREIGN KEY.
    Grault CHAR(30) NOT NULL,
    Garply CHAR(30) NOT NULL,   
    Plugh  CHAR(30) NOT NULL, 
    --
    CONSTRAINT Boat_PK         PRIMARY KEY (BoatId),
    CONSTRAINT Boat_to_Item_FK FOREIGN KEY (BoatId)
        REFERENCES Item (ItemId)  
);

CREATE TABLE Plane ( -- Denotes one of the subtypes.
    PlaneId INT      NOT NULL, -- Must be constrained as (a) the PRIMARY KEY and (b) a FOREIGN KEY.
    Xyzzy   CHAR(30) NOT NULL,
    Thud    CHAR(30) NOT NULL,  
    Wibble  CHAR(30) NOT NULL,
    Flob    CHAR(30) NOT NULL,  
    --
    CONSTRAINT Plane_PK         PRIMARY KEY (PlaneId),
    CONSTRAINT Plane_to_Item_PK FOREIGN KEY (PlaneId)
        REFERENCES Item (ItemId)  
);

As shown, the super entity type and each of the sub entity types are represented by the corresponding ones base Table.

The columns CarId. BoatId and PlaneId, constrained as the PKs of the corresponding tables, help in presenting the one-to-one mapping at the conceptual level via FK constraints§ this point on the ItemId Column, which is restricted as PK Item Table. This means that in an actual "pair," both the supertype and subtype rows are identified by the same PK value. Therefore, it is more than appropriate to mention this

  • (a) append a extra Column for system-controlled substitute values to (b) the tables for the subtypes are (c) totally unnecessary,

§ In order to avoid problems and errors with respect to (especially FOREIGN) KEY constraint definitions (situation referred to in the comments), it is very important to consider this existence dependency This is done under the different tables, as shown in the declaration order of the tables in the DDL structure of the Expositorys, which I have also specified in this SQL violin.

For example, appending an additional column with the AUTO_INCREMENT property to a table of a database based on MySQL.

Integrity and consistency considerations

It is important to note that in your business environment (1) you must ensure that each "supertype" line is supplemented at all times by the corresponding "subtype" counterpart, and (2) that this is guaranteed. The line is "subtype" compatible with the value in the Discriminator column of the Supertype row.

It would be very elegant to enforce such circumstances in a case declaratively Unfortunately, as far as I know, none of the major SQL platforms have provided the right mechanisms for doing so. Therefore, it is very convenient to use procedure code within ACID TRANSACTIONS to ensure that these conditions are always met in your database. Another possibility would be the employment of TRIGGERS, but they tend to make things messy, so to speak.

With a logical design like that explained above, it would be very convenient to make one or more views, i. E. derived Tables that contain columns that belong to two or more of the relevant ones base Tables. This way, you can, for example, SELECT directly from these views without having to write all the JOINs each time you need to retrieve "combined" information.

example data

In this context, suppose that the base tables are "filled" with the following sample data:

--

INSERT INTO UserProfile 
    (UserId, FirstName, LastName, BirthDate, GenderCode, Username, CreatedDateTime)
VALUES
    (1, 'Edgar', 'Codd', '1923-08-19', 'M', 'ted.codd', CURDATE()),
    (2, 'Michelangelo', 'Buonarroti', '1475-03-06', 'M', 'michelangelo', CURDATE()),
    (3, 'Diego', 'Velázquez', '1599-06-06', 'M', 'd.velazquez', CURDATE());

INSERT INTO Category 
    (CategoryCode, Name)
VALUES
    ('C', 'Car'), ('B', 'Boat'), ('P', 'Plane');

-- 1. ‘Full’ Car INSERTion

-- 1.1 
INSERT INTO Item
    (ItemId, OwnerId, CategoryCode, Foo, Bar, Baz, CreatedDateTime)
VALUES
    (1, 1, 'C', 'This datum', 'That datum', 'Other datum', CURDATE());

 -- 1.2
INSERT INTO Car
    (CarId, Qux, Corge)
VALUES
    (1, 'Fantastic Car', 'Powerful engine pre-update!');

-- 2. ‘Full’ Boat INSERTion

-- 2.1
INSERT INTO Item
  (ItemId, OwnerId, CategoryCode, Foo, Bar, Baz, CreatedDateTime)
VALUES
  (2, 2, 'B', 'This datum', 'That datum', 'Other datum', CURDATE());

-- 2.2
INSERT INTO Boat
    (BoatId, Grault, Garply, Plugh)
VALUES
    (2, 'Excellent boat', 'Use it to sail', 'Everyday!');

-- 3 ‘Full’ Plane INSERTion

-- 3.1
INSERT INTO Item
  (ItemId, OwnerId, CategoryCode, Foo, Bar, Baz, CreatedDateTime)
VALUES
  (3, 3, 'P', 'This datum', 'That datum', 'Other datum', CURDATE());

-- 3.2
INSERT INTO Plane
    (PlaneId, Xyzzy, Thud, Wibble, Flob)
VALUES
    (3, 'Extraordinary plane', 'Traverses the sky', 'Free', 'Like a bird!');

--

Then one advantageous view is one from which columns are collected Item. Car and UserProfile:

--

CREATE VIEW CarAndOwner AS
    SELECT C.CarId,
           I.Foo,
           I.Bar,
           I.Baz,
           C.Qux,
           C.Corge,           
           U.FirstName AS OwnerFirstName,
           U.LastName  AS OwnerLastName
        FROM Item I
        JOIN Car C
          ON C.CarId = I.ItemId
        JOIN UserProfile U
          ON U.UserId = I.OwnerId;

--

Of course, a similar approach can be followed, so you can also choose the "full" one. Boat and Plane Information directly from a single table (in these cases a derivative).

Then, if you do not care about the presence of NULL marks in result sets, you can use the following VIEW definition to "gather" columns from the tables, for example: Item. Car. Boat. Plane and UserProfile:

--

CREATE VIEW FullItemAndOwner AS
    SELECT I.ItemId,
           I.Foo, -- Common to all Categories.
           I.Bar, -- Common to all Categories.
           I.Baz, -- Common to all Categories.
          IC.Name      AS Category,
           C.Qux,    -- Applies to Cars only.
           C.Corge,  -- Applies to Cars only.
           --
           B.Grault, -- Applies to Boats only.
           B.Garply, -- Applies to Boats only.
           B.Plugh,  -- Applies to Boats only.
           --
           P.Xyzzy,  -- Applies to Planes only.
           P.Thud,   -- Applies to Planes only.
           P.Wibble, -- Applies to Planes only.
           P.Flob,   -- Applies to Planes only.
           U.FirstName AS OwnerFirstName,
           U.LastName  AS OwnerLastName
        FROM Item I
        JOIN Category IC
          ON I.CategoryCode = IC.CategoryCode
   LEFT JOIN Car C
          ON C.CarId = I.ItemId
   LEFT JOIN Boat B
          ON B.BoatId = I.ItemId
   LEFT JOIN Plane P
          ON P.PlaneId = I.ItemId               
        JOIN UserProfile U
          ON U.UserId = I.OwnerId;

--

The code of the views shown here is for illustrative purposes only. Of course, some testing exercises and changes may help speed up the (physical) execution of the queries that are present. Additionally, you may have to remove or add columns to these views, depending on the business needs.

The sample data and all view definitions are included in this SQL violin so they can be watched "in action".

Data manipulation: application program code and column aliases

The use of application program code (if you mean "server-side specific code") and column aliases are other important issues that you have addressed in the next few comments:

  • I managed to bypass a server-side code JOIN problem, but I really do not want to do that – and adding aliases to all columns could be "stressful".

  • Very well explained, thank you. However, as I suspected, because I do not want to use multiple aliases to make the statement clearer, I have to manipulate the result set when listing all the data because of the similarities with a few columns.

It should be noted that the use of application program code is a very appropriate resource for representing (or graphing) result sets. However, to avoid execution speed issues, it is very important to avoid retrieving data line by line. The goal should be to fully retrieve the relevant records using the robust data manipulation tools provided by the (well) specified engine of the SQL platform so you can optimize the behavior of your system.

Using aliases to rename one or more columns in a particular area may seem stressful, but I personally see such a resource as a very powerful tool that helps (i) determine the context and (ii) disambiguate it meaning and intention attributed to the relevant columns; Therefore, this is an aspect that should be thoroughly considered in terms of the manipulation of the data of interest.

You might as well find help with this series of posts and this group of posts that include my view of two other cases involving associations between superspecies and subtypes with mutually exclusive subtypes.

I have also suggested a solution for a business environment with a supertype subtype cluster in which the subtypes exist Not close each other out in this (newer) answer.


1Integration definition for information modeling (IDEF1X) is a highly recommended data modeling technique known as default in December 1993 from the USA National Institute of Standards and Technology (NIST). It is based on (a) some theoretical work of the sole author the relational model, d. H. Dr. E.F. Codd; to (b) Dr. med. P. P. Chen developed entity relationship view; and also (c) the Logical Database Design Technique, written by Robert G. Brown.

2 In IDEF1X, a role name is a unique name assigned to an FK property (or attribute) to express the meaning it has within its entity type.

3 The IDEF1X standard defines key migration as "The modeling process of placing the primary key of a parent or generic object in its child object or its category as foreign key".

Implementation of N-tier with entity framework and repo pattern

I try to clean up this code, but I can not figure out how to best handle it.

The UI accesses the business layer and should not know about it EFContext In doing so, I get an almost exact copy of the EFContext Class in my RepoBase Class. If I need an entity-specific method, I'll create an entity-specific repo and derive it from the entity RepoBase

MS examples seem to skip RepoBase and only implement each CRUD method in each entity.

RepoBase offers separation, but at the expense of duplication. I would like to know if there is a better way.

Data Access Layer

public interface IDataContext
{
    T GetById(int id);
    void Delete(T entity);
}

public class EFContext : DbContext, IDataContext
{
    public virtual DbSet Student { get; set; }

    public T GetById(int id)
    {
        ...
    }

    public void Delete(T entity)
    {
        ...
    }

}

Business Logic Layer

// Generic repo
public class RepoBase
{
    private IDataContext _context;

    public RepoBase(IDataContext context)
    {
        _context = context;
    }

    public T GetById(int id)
    {
        return _context.GetById(id);
    }
}

// Specific repo
public class StudentRepo : RepoBase
{
    public Student GetByStudentId(int studentId)
    {
        ...
    }
}