Entity Framework Core table configuration - sql-server

I need help to configure table using IEntityTypeConfiguration, problem is that it creates table, but I can't choose maximum variable range.
I tried exact same code with modelbuilder and perfectly works, but in different classes no, and also warning message pops up:
No store type was specified for the decimal property 'ProductPrice' on entity type 'Product'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values in 'OnModelCreating' using 'HasColumnType', specify precision and scale using 'HasPrecision', or configure a value converter using 'HasConversion'
This message appears for every decimal variable, but not a single column range is right.
Here is my code:
public class ProductConfig : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Product");
builder.HasKey(e => e.Id);
builder.Property(e => e.ProductName)
.IsRequired()
.HasMaxLength(30);
builder.Property(e => e.ProductNumber)
.IsRequired(false)
.HasMaxLength(50);
builder.Property(e => e.Color)
.IsRequired(false)
.HasMaxLength(15);
builder.Property(e => e.ProductPrice)
.IsRequired()
.HasColumnType("decimal(10, 2)");
builder.Property(e => e.ShippingPrice)
.IsRequired()
.HasColumnType("decimal(10,2)")
.HasDefaultValue(0);
builder.Property(e => e.ShippingDimensions)
.IsRequired(false)
.HasMaxLength(40);
builder.Property(e => e.ShippingWeight)
.HasColumnType("decimal(6,1)")
.IsRequired(false);
builder.Property(e => e.Describtion)
.IsRequired(false)
.HasMaxLength(100);
builder.Property(e => e.ModifiedDate)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
builder.Property(e => e.PhotoFileName)
.HasMaxLength(100);
builder.HasOne(e => e.ActivatedAccount)
.WithMany(a => a.Products)
.HasForeignKey(e => e.AccountId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(e => e.Category)
.WithMany(c => c.Products)
.HasForeignKey(e => e.CategoryId)
.OnDelete(DeleteBehavior.NoAction)
.IsRequired(false);
}
}

Related

Cannot insert duplicate key row in object 'dbo.AspNetUsers' with unique index 'IX_AspNetUsers_RegistrarId'

I have extended IdentityUser in ASP.NET-Core 3.1 application using EF-Core 3.1 on Visual Studio 2019 and I have the following fields defined
public class ApplicationUser : IdentityUser
{
public string Surname { get; set; }
public string OtherNames { get; set; }
...
public string RegistrarId { get; set; }
...
[ForeignKey("RegistrarId")]
public virtual ApplicationUser Registrar { get; set; }
....
}
This is the fluentApi for all the entities where some further relationships are required
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(b =>
{
// Each User can have many UserClaims
b.HasMany(e => e.Claims)
.WithOne(e => e.User)
.HasForeignKey(uc => uc.UserId)
.IsRequired();
// Each User can have many UserLogins
b.HasMany(e => e.Logins)
.WithOne(e => e.User)
.HasForeignKey(ul => ul.UserId)
.IsRequired();
// Each User can have many UserTokens
b.HasMany(e => e.Tokens)
.WithOne(e => e.User)
.HasForeignKey(ut => ut.UserId)
.IsRequired();
// Each User can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.User)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
b.HasIndex(e => e.Email)
.IsUnique();
});
modelBuilder.Entity<ApplicationRole>(b =>
{
// Each Role can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
// Each Role can have many associated RoleClaims
b.HasMany(e => e.RoleClaims)
.WithOne(e => e.Role)
.HasForeignKey(rc => rc.RoleId)
.IsRequired();
b.HasMany(e => e.RoleRoutes)
.WithOne(e => e.Role)
.HasForeignKey(c => c.RoleId)
.IsRequired();
});
modelBuilder.Entity<RatedGroupCriterion>()
.HasKey(rc => new {
rc.RatedGroupId,
rc.CriterionId
});
modelBuilder.Entity<RatedGroupCriterion>()
.HasOne(reg => reg.RatedGroup)
.WithMany(rgc => rgc.RelatedCriteria)
.HasForeignKey(reg => reg.RatedGroupId);
modelBuilder.Entity<RatedGroupCriterion>()
.HasOne(rc => rc.Criterion)
.WithMany(rgc => rgc.RelatedEntities)
.HasForeignKey(reg => reg.CriterionId);
modelBuilder.Entity<InstructorCriterionRating>()
.HasKey(irc => new { irc.InstructorRatingId, irc.CriterionId });
modelBuilder.Entity<LessonCriterionRating>().HasKey(lrc => new { lrc.LessonRatingId, lrc.CriterionId });
modelBuilder.Entity<RoleErrand>().HasKey(rap => new { rap.RoleId, rap.ErrandId });
modelBuilder.Seed();
}
but I realized that after inserting the first record into the database table, I am having problem inserting further records into the same table and the error I get is as follows
Cannot insert duplicate key row in object 'dbo.AspNetUsers' with unique index 'IX_AspNetUsers_RegistrarId'. The duplicate key value is (d75c86d4-32d8-4b34-8269-b31e3fd35d58). The statement has been terminated.
On checking the design view of my users table I saw the following
CREATE UNIQUE NONCLUSTERED INDEX [IX_AspNetUsers_RegistrarId]
ON [dbo].[AspNetUsers]([RegistrarId] ASC)
WHERE ([RegistrarId] IS NOT NULL);
Therefore giving a unique constraint on the RegistrarId column but I cannot find where I added that condition/constraint or where/how to remove it properly. And because of this, I cannot continue adding more records to the database table.
Please help me if you can guide me on how to rectify this issue
Thank you

in_array() expects parameter 2 to be array, null given in Laravel Controller

I have two request sample and incomplete sample, I get the complete sample by submitting the form without ticking any checkbox, then get incomplete samples by clicking the checkbox.
I can get incomplete samples by ticking the checkbox. I get the error while getting the complete samples.
if(!in_array($sample, $request->pending)){
$tests = Session('tests');
$createSample = Sample::create([
'test_user_id' => $request->test_user_id,
'received_by' => (integer)$request->received_by,
'received_at' => $now,
'received_name' => $request->received_name,
'biobank' => $request->biobank,
'order_id' => $request->order_id,
'order_type' => $request->order_type,
'name' => $request->name,
]);
Its because if you don't check the checkbox, the value won't submit and hence the $request->pending will be null instead of an array. You can try to check if its null and then you can do whatever you want to do with it.
if($request->pending){
if(!in_array($sample, $request->pending)){
$tests = Session('tests');
$createSample = Sample::create([
'test_user_id' => $request->test_user_id,
'received_by' => (integer)$request->received_by,
'received_at' => $now,
'received_name' => $request->received_name,
'biobank' => $request->biobank,
'order_id' => $request->order_id,
'order_type' => $request->order_type,
'name' => $request->name,
]);
}
}

Drupal 7 failure to create an entity of a fieldable type I created because of null id

I am writing my first module and have created a fieldable entity. The only property of the entity in its schema is an 'id' which is type serial, unsigned and not null. However when I use entity_create (with no property values set) followed by $entity->save() the code fails with the following SQL error:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'entity_id' cannot be null: INSERT INTO {field_data_field_available} (entity_type, entity_id, revision_id, bundle, delta, language, field_available_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => appointments_status [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => [:db_insert_placeholder_3] => appointments_status [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => No ) in field_sql_storage_field_storage_write() (line 514 of C:\wamp\www\Drupal\modules\field\modules\field_sql_storage\field_sql_storage.module).
This implies to me that Drupal is trying to create entries in the 'field_data' table before it has created the entry in the entity table. I set no property values because I only have the 'id' property and surely that should be auto generated. If this was done first then it would have the id for creating the entry in the field_data table. The exact code I used is:
$entity_record = entity_create($entity_name,array());
$entity_record->save();
I hope someone has clues. The only work around I can see is to count the existing records, add one and use that as the new id but I can see loads of issues with this approach (clashing ids, performance etc).
Work around code:
$entities = entity_load('my entity type');
$entity_id = count($entities) + 1;
// Create the new entity object with this ID
$entity = entity_create('my entity type, array('id' => $entity_id));
// Save the new entity ready to reload after this if block of code
$entity->save();
My hook_entity_info is:
function appointments_entity_info() {
return array(
'appointments_status' => array(
'label' => t('Appointment status'),
'default label' => t('Appointment status'),
'plural label' => t('Appointment statii'),
'entity class' => 'Entity',
'controller class' => 'EntityAPIController',
'views controller class' => 'EntityDefaultViewsController',
'base table' => 'appointments_status',
'entity keys' => array(
'id' => 'id'
),
'fieldable' => TRUE,
// Create one default bundle of the same name
'bundles' => array(
'appointments_status' => array(
'label' => t('Appointment statii'),
),
),
// Use the default label() and uri() functions
'label callback' => 'entity_class_label',
'uri callback' => 'entity_class_uri',
'module' => 'appointments',
),
);
}
Thanks
Rory
Thanks very much to #Arkreaktor for pointing me in the right direction. I added a 'bundle' property to my schema - type varchar length 255. I made no changes to hook_entity_info to refer to this property but then changed my entity create code to:
$entity = entity_create($entity_type, 'bundle' = $entity_type);
$entity->save();
$entity_id = $entity->id;
// Re-load the new entity or loading the existing entity
$entity = entity_load_single($entity_type, $entity_id);
// Rebuild the entity object from the values on the form
entity_form_submit_build_entity($entity_type, $entity, $form, $form_state);
// Save updated entity
$entity->save();
And it worked!!!
I hope this helps others.
Rory

Memcached setup with cakephp3

I am setting up memcache setup with cakephp3. I added below in config/app.php
'Cache' => [
'default' => [
'className' => 'Cake\Cache\Engine\MemcachedEngine',
],
]
On the top of the controller I added
use Cake\Cache\Cache;
use Cake\Cache\CacheEngine;
use Cake\Cache\CacheRegistry;
But when I used any function of memcache like Cache::write('variable','value'); etc
It is giving me error
" Error: Cache engine Cake\Cache\Engine\MemcachedEngine is not properly configured. "
The memcached is installed on server.. here is the output
/etc/php.d/memcache.ini,
memcache
memcache support => enabled
memcache.allow_failover => 1 => 1
memcache.chunk_size => 32768 => 32768
memcache.compress_threshold => 20000 => 20000
memcache.default_port => 11211 => 11211
memcache.hash_function => crc32 => crc32
memcache.hash_strategy => consistent => consistent
memcache.lock_timeout => 15 => 15
memcache.max_failover_attempts => 20 => 20
memcache.protocol => ascii => ascii
memcache.redundancy => 1 => 1
memcache.session_redundancy => 2 => 2
Please let me know what is the remaining in configuration. Thanks in advance.
Wrong extension
There are two php extensions related to memcache:
Memcache (older)
Memcached (newer, more features)
The CakePHP Memcached driver relies on memcacheD:
if (!extension_loaded('memcached')) {
return false;
}
Which will result in that error message if it's missing:
if (!$instance->init($config)) {
throw new RuntimeException(
sprintf('Cache engine %s is not properly configured.', get_class($instance))
);
}

Laravel 4 - A four digit year could not be found Data missing

I'm trying to update some data and I'm having the next message:
A four digit year could not be found Data missing
In this form, I have some data that I want to update in my 'Actividad', so I have created an array with every field I need to update.
But, one of the form fields, I don't want to put it in the same array, because I need it to update the data in a pivot table ('actividad_material').
By the moment, I'm not able to update any of them... :(
Here is my code:
public function update($id)
{
$input = array(
'titulo' => Input::get('titulo'),
'actividad' => Input::get('actividad'),
'datos' => Input::get('datos'),
'solucion' => Input::get('solucion'),
'minutos' => Input::get('minutos'),
'tipo_id' => Input::get('tipo_id'),
'asignatura_id' => Input::get('asignatura_id'),
'bloque_id' => Input::get('bloque_id'),
'contenido_id' => Input::get('contenido_id'),
'objetivo_id' => Input::get('objetivo_id'),
'nivel_id' => Input::get('nivel_id'),
'etapa_id' => Input::get('etapa_id'),
'm_desc' => Input::get('m_desc'),
'slug' => Str::slug(Input::get('titulo')),
'user_id' => Sentry::getUser()->id,
'_method'
);
$v = Validator::make($input, Actividad::$rules);
if($v->passes())
{
// Trying to update my pivot table...
$actividad = Actividad::find($id);
$material_id = array(
'material_id' => Input::get('material_id'));
$actividad->materials->sync($material_id);
Actividad::find($id)->update($input);
return Redirect::route('actividads.index');
}
return Redirect::back()->withErrors($v);
}
Any idea why I'm getting this error? Maybe the timestamps?
What am I doing wrong when updating?
Thank you very much in advance!!

Resources