c# – Bulk update entity with its navigation properties in ef core using CQRS

I am using EF core and CQRS. I have a command which updates some records.
each record has zero or more images. I have implemented this code, but I wonder to know is there a better way.

public class UpdateSetTypesCommandHandler : RequestHandler<UpdateSetTypesCommand>
{
    private readonly DataContext _dataContext;
    public UpdateSetTypesCommandHandler(DataContext dataContext)
    {
        _dataContext = dataContext;
    }

    protected override void Handle(UpdateSetTypesCommand request)
    {
        var setTypes = _dataContext.SetTypes
            .Include(s => s.Images)
            .Where(s => request.SetTypes.Select(r => r.Id).Contains(s.Id)).AsNoTracking().ToList();
        foreach (var setType in request.SetTypes)
        {

            var setTypeDb = setTypes.Single(s => s.Id == setType.Id);
            setTypeDb.Images.Clear();
            setTypeDb = setType;
            _dataContext.Attach(setTypeDb);
            _dataContext.Entry(setTypeDb).State = EntityState.Modified;
        }
    }
}

The relation between SetType and Image is many to many. SetTypeImage table is like this:

 public class SetTypeImage
{
    public int SetTypeId { get; set; }
    public virtual SetType SetType { get; set; }
    public int FileId { get; set; }
    public virtual File File { get; set; }
}

testing – Simulate SqlConnectionException with Simmy and Entity Framework

I’m trying to use Simmy to test service resilience in case of failure. I’ve found Simmy which looks promising but my guess is that is can only be used along with Polly. Since my main point of failure can be the database connection, I would like to inject failure at the Entity Framework part of the code. Is that possible with Simmy? Or is there any other way to inject failure on the Entity Framework side for some chaos engineering?

c# – How should I work around a particular “chicken and egg” problem with entity construction?

I’m struggling to think of a concise way to phrase the question, but assume you were developing an application that managed employees at various company branches. You could potentially model this part of the application like this:

branch and employees example

It’s stipulated that every employee must belong to exactly one branch. To enforce this, you’d pass the branch the employee operates at to the Employee constructor and make the corresponding property immutable:

class Employee {

    public Employee(int id, string name, Branch operatesAt)
    {
        Id = id;
        Name = name;
        OperatesAt = operatesAt;
    }

    public int Id { get; }
    public string Name { get; }
    public Branch OperatesAt { get; }
}

You might then choose to model the Branch class like this:

class Branch {

    private readonly List<Employee> _employees;

    public Branch(int id, string name, ICollection<Employee> employees)
    {
        Id = id;
        Name = name;
        _employees = employees.ToList();
    }

    public int Id { get; }
    public string Name { get; }
    public IReadOnlyCollection<Employee> Employees => _employees.AsReadOnly();
}

In my application I’m using EF Core, and something similar to these models would work fine. I’m following Microsoft’s architectural recommendations for ASP.NET Core development, and as such I’m trying to use a domain-driven approach to modelling the entities that EF Core operates with. This is why I’m trying to use constructors to ensure my entities can only ever exist in a valid state and prevent mutation of these entities except through methods that represent domain-relevant operations.

However, trying to manually setup a new branch with employees (for example, in tests) exposes a chicken and the egg problem:

var branch = new Branch(id: 1, name: "Example branch", employees: new()
{
    new ProductConsultant(id: 12345, name: "John Smith", operatesAt: um...)
});

Is this a common issue to run into, and if so is there a well-defined solution to it? Someone I discussed this with mentioned the builder pattern could work. An alternative that I’m thinking of going with is to define a factory method on the principal entity that constructs, registers and returns an instance of the dependent entity:

class Branch {

    private readonly List<Employee> _employees;

    public Branch(int id, string name)
    {
        Id = id;
        Name = name;
        _employees = new List<Employee>();    
    }

    public int Id { get; }
    public string Name { get; }
    public IReadOnlyCollection<Employee> Employees => _employees.AsReadOnly();

    public Employee RegisterNewEmployee(int id, string name)
    {
        var employee = new Employee(id, name, this);
        _employees.Add(employee);
        return employee;
    }
}

Is this a suitable approach, or is there something more appropriate that can be done here?

theming – How to use hook_field_preprocess to add a prefix/suffix to an entity reference field for different view modes?

I’m trying to move some markup from twig templates to hook_preprocess_field().

I have an entity reference field (media image) that I want to add a prefix and suffix to.

I added a prefix and suffix like this:

function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  $prefix = 'Hi... ';
  $view_mode = $variables('element')('#view_mode');
  if ($view_mode == 'second_view_mode') {
    $prefix = 'Hello... ';
  }
  $suffix = '... there.';
  $variables('items')(0)('content')('#prefix') = $prefix;
  $variables('items')(0)('content')('#suffix') = $suffix;
}

With this code, my prefix and suffix get added, but they are cached, and the same for all view modes.

If I rebuild the cache and visit a node in second_view_mode, then I see Hello... as the prefix for all instances of the field. But if I rebuild the cache and visit a node not in second_view_mode, then I see Hi... for all instances of the field, even those on a node in second_view_mode.

I use this same approach/code for formatted text fields and I don’t experience this caching problem. So I think I need to do something different for this entity reference field, but I don’t know what to do.

How do I add a prefix/suffix to an entity reference field in a preprocess function for different view modes?

c# – A simple method to execute Entity Framework Core queries in parallel

As you might know, EF Core does not support executing multiple queries in parallel on the same context using something like Task.WhenAll.

So you have to write this code instead:

using var context1 = _factory.CreateDbContext();
using var context2 = _factory.CreateDbContext();
using var context3 = _factory.CreateDbContext();

var result1Task = context1.Set<T1>().ToListAsync();
var result2Task = context2.Set<T2>().ToListAsync();
var result3Task = context3.Set<T3>().ToListAsync();

await Task.WhenAll(result1Task, result2Task, result3Task);

var result1 = result1Task.Result;
var result2 = result2Task.Result;
var result3 = result3Task.Result;

To get rid of all these using statements, I started writing a library which exposes a Set<TEntity() extension method on IDbContextFactory<TContext>. You can use it like this.

var result1Task = _factory.Set<T1>().ToListAsync();
var result2Task =  _factory.Set<T2>().ToListAsync();
var result3Task =  _factory.Set<T3>().ToListAsync();

await Task.WhenAll(result1Task, result2Task, result3Task);

var result1 = result1Task.Result;
var result2 = result2Task.Result;
var result3 = result3Task.Result;

To achieve this, it heavily relies on reflection and EF Core internals. And because of this, I would really like a code review from someone experienced with EF Core, Expressions and IQueryable.

What it basically does is, it creates an IQueryable<TEntity> which is then exchanged for a real DbSet<TEntity> once it is executed and immediately disposes the context after that. When using the async version, it is a bit more complex. It passes down the DbContext to the AsyncEnumerator and disposes the context together with the AsyncEnumerator.

It is too much code to post here, you can find it on Github https://github.com/wertzui/EntityFrameworkCore.Parallel

Tank you in advance.

theming – How do I include data from commerce_order entity in the order receipt email (twig)?

Stack Exchange Network


Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

theming – Entity Print PDF stying issues

How can I apply CSS styling to a PDF generated from node content?

Using the Entity Print module I am able to create PDFs from my node content.
My problem is the PDF output do not reflect the styling I am applying to it. For example, the http://localhost:85/print/pdf/node/2 is the PDF url but it is entirely deviod of my styling despite my continued efforts.

Using the TCPDF (v1) pdf engine and having followed the pertinent instructions at this link, I have the following configuration code:

In mytheme.info.yml:

entity_print:
  node:
    deal: 'oliverock/deal-pdf-styling'

And in mytheme.libraries.yml:

deal-pdf-styling:
  css:
    theme:
      css/deal.css: {}

And deal.css is quite simple:

* {
    color: red;
}

div {
    background: blue;
}

As I alluded to above, I expected that simple styling to take effect in my PDFs but it’s all just black text on a white background.
And for the longest time I assumed my code was at fault until I noticed the debug line in the instructions.

All my code is visible at http://localhost:85/print/pdf/node/2/debug but that output is not a PDF.

I would appreciate some help please.

How to create entity array in mftf data?

I have this code defined on my shop-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd">
    <operation name="CreateShops" dataType="shops" type="create" auth="anonymous" url="/V1/shop" method="POST">
        <contentType>application/json</contentType>
        <object dataType="shops" key="shops">
            <array key="shops">
                <value>Shop</value>
            </array>
        </object>
        <object dataType="Shop" key="Shop">
            <field key="shop_id">integer</field>
            <field key="shop_name">string</field>
            <array key="services">
                <value>Service</value>
            </array>
        </object>
        <object dataType="Service" key="Service">
            <field key="service_id">integer</field>    
            <field key="service">string</field>
            <field key="service_name">string</field>
            <field key="waiting_time_seconds">integer</field>
            <field key="tickets_in_queue">integer</field>
            <field key="current_ticket">string</field>
        </object>
    </operation>
</operations>

How can I create an entity of the object shops in my ShopData.xml?

7 – When a Boolean property in ECK isn’t added to the entity edit form, it is automatically unchecked. Why?

So I have an ECK entity type with a boolean property called “status”, similar to the node “publish” boolean.
I use Page Manager to control what fields and properties will be loaded on the entity EDIT form.
Now it appears that if I don’t show/load my boolean property form on the entity EDIT form AND if it was set previously to “checked” (1), after saving it now becomes “unchecked” (0).
I believe that shouldn’t happen but I don’t understand why it happens.
I don’t want users to be able to tick or untick this checkbox when they update it.

Is this the normal behavior?

When a boolean property in ECK (Drupal 7) is not added to the entity EDIT form, it is automatically unchecked. Why?

So I have an ECK entity type with a boolean property called “status”, similar to the node “publish” boolean.
I use Page Manager to control what fields and properties will be loaded on the entity EDIT form.
Now it appears that if I don’t show/load my boolean property form on the entity EDIT form AND if it was set previously to “checked” (1), after saving it now becomes “unchecked” (0).
I believe that shouldn’t happen but I don’t understand why it happens.
I don’t want every user to be able to tick or untick this checkbox when they update it.

Is this the normal behaviour?