Validating against a duplicate entry in ASP.NET 5 MVC 6 - asp.net-core

Using asp.net 5, MVC 6, code first, entity Framework 7, beta 8.
I understand that some validation can be handled through annotations on properties, e.g. Data Type, min, max values and the jquery scripts, but I'm not sure how in code validation against a duplicate entry getting into the database, like preventing a duplicate e-mail reg on a form.
Is there any annotation that I can use for this on my model property or do I need to code something in my controller to handle this custom validation? Anyone got an example to share?

EF7 does not have any magic to prevent duplicate values in a table. The only way to validate duplicates is to make a roundtrip to the database. The best way to do this is with a unique constraint. This may be expressed as a unique index. Any attempt to insert a duplicate entry should throw an exception.
That said, you can configure EF7 to recognize the unique index in your database in your OnConfiguring method. See Indexes : Configuring Your Model in the EF7 docs.
modelBuilder.Entity<User>()
.Index(b => b.Email)
.Unique();

Related

Add, Update and delete using single transaction EF 6?

I have method which has following signature
performAmmend(Project project, List witem, List cConfig)
the relationship is
Project->WorkItem ( 1 to many)
WorkItem->CustomConfig( 1 to many )
List parameter could have some new entries, modified or deleted
How to perform update operation for the project using transaction?
i am using code first approch in Entity framework 6.x.
EF will give you a transaction by default. So simply setup your object graph and apply SaveChanges(). OK, deep object graphs aren't simple, but you could use a tool like graphdiff

Read from table, infer counter and insert on database using entity framework 5 and mvc 4

I have this situation. I have a table called Request. This table has a column named Number. Every time I want to insert a new Request then I fetch the last request and based on its Request Number I infer a new one.
For example, I have on my database Request1 with number 0001 then when I will insert a new one I fetch Request1 and based on its Number I infer my new Request Number which should be 0002.
The problem occurs when I want to create two Requests simultaneously. Process one fetch the Request1 and process two also gets Request1. When process one infers the new request number, which should be 0001, process two do the same. At the end I will create two new requests with the same Number.
Someone knows how to solve this?
Sorry about my english! ;)
There are several ways to solve your problem.
The field is always numeric, sequential, and each record the value must be higher than the last record?
If it is, you simply let the database do the work for you. Just set the field in question as the primary key of the table and how identity. In this case the database will provide the solution to internal competition, and of course to prevent ending up getting duplicate records. And the number is automatically filled by the DBMS (SQL Server, MySQL, Oracle ...)
If you are using EntityFramework and Code First, just go in the declaration of the entity (a C # class that defines the table in the database) and locate the field you need and add 2 attributes to him:
// Probably you have this kind of code (which fieldID should be the field name)
public Int32 fieldID {get; set;}
// Just add these two attributes before the declaration of the field
[Key]
[DatabaseGenerated (DatabaseGeneratedOption.Identity)]
public Int32 fieldID {get; set;}
/* Example in C#, assuming you are using SQL Server and EFCF */
/* EF CF means Entity Framework Code First! */
You need to implement a logic to populate this field, which may not be as described above, or the field is not numeric or can not be done by the database and have to be direct by your application?
You can implement a lock on straightforward piece of code that can not have competition.
In the class that makes the manipulation of data and you are encountering the problem declare a variable of type Object, static and read-only like this:
private static readonly Object concurrencyLock = new Object ();
In the method that implements the logic that needs to be accessed uniquely enclose the code with a lock policy
lock(concurrencyLock) {
//Do stuff here without concurrency
/* When the current request into this part of the code,
any other request will execute until the line above with "lock" statement.
Until this current request exit this "lock" block of code,
the other(s) will wait. As this one leave this block, one other join...
One at a time as you wish. */
}
There are others ways to do that too, but is a bit more complex or dosen't work well in a Web Application (like a Mutex, that would work fine if it's a Windows Service, ou Windows Form application)

Include count of linked records in OData result

I've got a table "Events" with a linked table "Registrations", and I want to create an OData service that returns records from the Events table, plus the number of registrations for each event. The data will be consumed client-side in JavaScript, so I want to keep the size of the returned data down and not include all linked registration records completely.
For example:
ID Title Date Regs
1 Breakfast 01.01.01 12:00 4
2 Party 01.01.01 20:00 20
I'm building the service with ASP.NET MVC4. The tables are in an MSSQL database. I am really just getting started with OData and LINQ.
I tried using the WebAPI OData system first (using classes of EntitySetController) but was getting cryptic server errors as soon as I included the Registrations table in the entity set. ("The complex type 'Models.Registration' refers to the entity type 'Models.Event' through the property 'Event'.")
I had more success building a WCF OData system, and can request event information and information on related registrations.
However, I have no clue how to include the aggregate count information in the event result set. Do I need to create a custom entity set that will be the source for the OData service? I probably included too litte information here for finding a solution, but I don't really know where to look. Can somebody help me?
If you're willing to make an extra request per Event, you could query http://.../YourService.svc/Events(<key>)/Registrations/$count (or http://.../YourService.svc/Events(<key>)/$links/Registrations?$inlinecount=allpages if you're also using the links to the Registration entities).
Examples of both of these approaches on a public service:
http://services.odata.org/V3/OData/OData.svc/Suppliers(0)/Products/$count
http://services.odata.org/V3/OData/OData.svc/Suppliers(0)/$links/Products?$inlinecount=allpages&$format=json
I'm guessing that you'd prefer this information to come bundled together with the rest of the Events response though. It's not ideal, but you could issue a query along these lines:
http://services.odata.org/V3/OData/OData.svc/Suppliers?$format=json&$expand=Products&$select=Products/ID,*
I'm expanding Products (analogous to your Registrations) and selecting Products/ID in order to force the response to include an array that is the same size as the nested Products collection. I don't care about ID -- I just chose a piece of data that would be small. With this JSON response, your javascript client can get the length of the Products array and use that as the number of Products that are linked to the given Supplier.
(Note: to have your service support $select queries using WCF Data Services, you'll need to include this line when you initialize the service: config.DataServiceBehavior.AcceptProjectionRequests = true;)
Edit to add: The approach using $expand and $select won't be guaranteed to give you the correct count if your server does server-driving paging. In general, there isn't a simple single-response way to do what you're asking for in OData v3, but in OData v4, this will be possible with the new expand/select syntax.
i'm using oData v4 and i used this syntax :
var url = '.../odata/clients?$expand=Orders($count=true)';
// ...
a field called Orders#odata.count has been added to the response entity which contains the correct count.
and now to access the JSON property containing a dash you have to do it like this :
var ordersCount = response.value['Orders#odata.count'];
hope this helps.
Can you edit your Event model and add a RegistrationCount property? That'd be the simplest way I think
What I ended up doing was actually very simple; I created a View in SQL Server that returns the table including the registration counts. Never thought about using a view, since I've never used them before...
I used this to get the child count without returning the entities:
/Parents$expand=Children($count=true;$top=0)

custom business logic in dataform in Silverlight 4

I am using Domain Services and Entity Framework. EF has account entity with 4 fields, ID,Name,Age, MyLogic
in My sample XAML file:
i have 3 fields for example ID, NAME,AGE.
While inserting and updating data, i have 3 values on XAML file and i need to insert custom logic into 4rth field. like
MyLogic= Name-Age-ID( new auto generated id from database)= eg Adam-58-NewPKValue
What is best practice to solve it.
Thanks,
R
There are several ways to implement a 'pseudo' property (i.e., a value that is not stored in the database, but computed from other values instead). If you are using the MVVM pattern, you can bind the field on the data form to a notifying property in your ViewModel.
In order for the dataform to be in synch, the mutators for your other three properties would have to invoke the setter of your 'pseudo' property. So that, for example, when the user changed the Name, the NameAgeId property would be simultaneously updated.

How do I get NHibernate to save an entity if I assign it an ID, but generate one otherwise?

According to the REST philosophy, a PUT request should update the resource at a URL if it exists, and create it if it doesn't exist. So in other words, if I use the following URL:
PUT http://server/item/5
If an Item exists with an ID of 5, it will be updated. If an Item doesn't exist with an ID of 5, a new Item will be created with an ID of 5.
However, I'm using NHibernate for persistence, and I mapped my IDs as Identity. This means that no matter what value I assign the ID, NHibernate will replace it with its own when I save a new Item.
How do I get NHibernate to save an Item with the ID that I assign it, without changing the ID mapping to Assigned?
If you use Identity, the DB won't allow you to enter a value.
That said, if your DB has some special syntax to allow inserting with explicit values in Identity fields, you can implement your own generator, which I guarantee will be error prone, hard to debug, and not very useful. But it's possible.
Study everything in https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Id and start creating your Frankenstein :-)