Avoid entity duplication with Linq in ASP.NET Core Web API - entity-framework

I want to know the best way of avoiding entity duplication in an ASP.NET Core Web API project.
Imagine that you have a product with a name and manufacturer and you want to make sure if the name is not duplicated. Imagine that a new product with a name came from client (dto) and we need to look if the name (entity) already exists in the database (using EF).
You need to trim the name (name.trim()) for both names from entity and dto
You need to remove all the whitespaces in between (string.replace(" ", string.empty())
You need to change everything to lower case (string.lower())
Finally you need to compare these two
Is there any best practices how to do this without writing all the code? I tried to use string.compare with the compareoptions like ignorecase and ignoresymbols and also the string.equal() with ignorecase option but the EF gives me an alarm that it can not translate the code.
br

I have a suggestion for your approach.
Introduce another column (This can be a primary key with other keys) and save the name with trimming and lowercase when you insert a new record to that table.
Example:
Original Name : Amir Masoud Babaei -->
New Column value: amirmasoudbabaei
And when you insert a new record, do your trimming and lowercase changes and save it to the database. Since it is a primary key, it should throw an error.
So with this approach, you don't need to loop through all the names and validate if the name is already exist.

Related

How to use Entity, Mapper, Service and Hydrator in ZF2

I am making a ZF2 app. I am using entities, mappers and services (e.g. UserEntity, UserMapper, UserService) to manage the objects/models. Properties in the entities are CamalCased (e.g. FirstName, LastName) while in the database, fields are using underscore (first_name, last_name). I will plan to use a hydrator to map the properties and db-fields when retrieving or saving. The service object (UserService) will be used to communicate with the mapper to retrieve and save data models using the mapper. The hydrator will convert the result of mapper and convert them into proper entities.
The thing I am confused is that when the service (UserService) need to provide some cirteria - for example to find all users with a specific 'last name', will the service use the database field names (last_name) or entity properties name (LastName)?
If the db field name is used in the Service, so any change in the db structure will require me to update the service also, which completely fails the reason of using the whole approach.
If you take a look at the ClassMethods:hydrate method (https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/Hydrator/ClassMethods.php) you will see that it just copies the properties from one object to another. You have the option of converting the property names to/from camelCase but that's it.
If you change a column name in your database then you will need to change corresponding property name in your object. And vice versa. Which I believe is the crux of your question?
If you want to make table column names be independent of your method names then you need something that lets you define an actual mapping table somewhere. Change a column or method name and you only need to update the configuration mapping table.
Not a ZF2 expert so I could be wrong but it doesn't look like any of the supplied hydrators support this.
I do know that Doctrine 2 supports it.

Firebird / Entity Framework foreign key names

Using the Firebird .NET Provider and Entity Framework (code first), foreign key names seem to be of this convention:
FK_MyNetClassName1_MyNetClassName2
This makes it very easy to go over Firebird's 30 character limit. Is there a way to control the foreign key names? (Could they be based on my much shorter table names instead of class name? Then they would be uppercase as well!)
You can't change it directly. The name creation is hardcoded (currently) in provider. But you can let code generate the script and change it there to whatever you want.

How should I write an Entity Framework migration that transforms data (preferably using the DbContext)?

Say my object has a Name field, and I wish to split it into FirstName and LastName fields. Or maybe it has an address string and I'm adding Lat and Lng fields that require geocoding. Etc etc.
I expected to have access to my DbContext in the Up() and Down() methods, but all I've been able to find (besides the builtin functions) is the .Sql() call. This is enough for adding and removing columns, but not for transforming existing data into new formats.
Is it safe to reference my DbContext inside an Up() invocation? Or is there another recommended pattern for implement migrations that require more than trivial SQL?
No you cannot use DbContext inside Up method because it already refers new model but your database still targets the old model.
Edit:
All data migrations must be done through Sql. You can for example create temporary table, move old data to temporary table, use migration of table structure and move data from temporary table back to the original with using some transformation directly in SQL - splitting varchar values should not be a big deal.
Rather than trying to split the Name into two different fields, rethink your migration. Sometimes it might be best staged. I can think of two ways to perform your transformation.
Migration path #1: New Fields, then Delete old
Create migration for new field for FirstName and LastName, and in the Up() method, you still have the Name field, split it, insert into First and Last fields.
Create another migration to remove the old Name field.
Migration path #2: Repurpose and Rename
Create a migration adding the LastName field, and renaming Name to FirstName, move the last name data, modify the renamed First/Name field to only hold the first name.
Both paths have advantages and disadvantages. And regardless of the complexity of your transformation, you should be able to break it out into logical stages to accomplish the goal.

Entity framework 4 model first using money value object

I want to use a Money value object in my application. I have found several examples of a Money datatype. But I can't figure out how to use them with EF4. I would like to store each amount as a Decimal/CurrencyCode pair (where currencycode is a string - "USD", "SEK", etc) in the database. I tried creating a complexType but I couldn't get that to work. Is this possible?
It should be definitely possible. Your complex type is just pair of decimal and string property. It is exactly what complex type are used for. Depending on your approach you must do:
Database first:
You will define your database first. Your table will contain money and varchar columns representing your new type. When you update your EDMX model from database it will include it as scalar properties to your entity. You must remove those properties. Then go to model browser and create new complex type. Return back to entity and add complex property of your new complex type. And at the end you must go to entity mapping and map your complex type to those database columns.
Here is basic tutorial from MSDN but from unknown reason they didn't include such elementary details like screenshots. Here is some video from channel9.
Model first:
This is similar to database first but you don't have to deal with database creation and mapping. It will be generated for you.
Code first (EF 4.1):
You must create separate class for your complex type and use it as property in your entity. You should not need to map it by default - mapping should be infered. If it doesn't work you can map complext type either by using ComplextTypeAttribute annotation or by defining mapping in DbModelBuilder.
I can further extend approach you need to use if you provide more details.

Query to database with 'primary key' on GoogleAppEngine?

I've made a guestbook application using Google App Engine(GAE):python and the client is running on iPhone.
It has ability to write messages on the board with nickname.
The entity has 3 fileds:
nickname
date
message
And I'm about to make another feature that user can post reply(or comment) on a message.
But to do this, I think there should a 'primary key' to the guestbook entity, so I can put some information about the reply on a message.
With that three fields, I can't get just one message out of database.
I'm a newbie to database. Does database save some kind of index automatically? or is it has to be done by user?
And if it's done automatically by database itself(or not), how can I get just one entity with the key??
And I want to get some advise about how to make reply feature generally also. Thanks to read.
Every entity has a key. If you don't assign a key_name when you create the entity, part of the key is an automatically-assigned numeric ID. Properties other than long text fields are automatically indexed unless you specify otherwise.
To get an entity if you know the key, you simply do db.get(key). For the replies, you probably want to use a db.ReferenceProperty in the reply entity to point to the parent message; this will automatically create a backreference query in the message to get replies.
Each entity has a key, it contains information such as the kind of entity it is, it's namespace, parent entities, and the most importantly a unique identifier (optionally user specifiable).
You can get the key of an entity using the key method that all entities have.
message.key()
A key can be converted to and from a URL-safe string.
message_key = str(message.key())
message = Message.get(message_key)
If the key has a user-specified unique identifier (key name), you can access it like this
message.key().name()
Alternatively, if a key name was not specified, an id will be automatically assigned.
message.key().id()
To assign a key name to an entity, you must specify it when creating the entity, you are not able to add/remove or change the key name afterwards.
message = Message(key_name='someusefulstring', content='etc')
message.put()
You will then be able to fetch the message from the datastore using the key name
message = Message.get_by_key_name('someusefulstring')
Use the db.ReferenceProperty to store a reference to another entity (can be of any kind)
It's a good idea to use key name whenever possible, as fetching from the datastore is much faster using them, as it doesn't involve querying.