简体   繁体   中英

How to ensure unique column value inside code?

I am learning ASP.NET MVC, and confused as to how can I ensure unique values for columns (username & email) for a table.

Can anybody help me with a sample code or a link to the tutorial which shows & explains this?

EDIT:

I know that I can apply an unique key constraint on my table columns and achieve it. However, I want to know how can I achieve it via ASP.NET MVC code?

UPDATE:

I wish to do a check in my application such that no duplicated values are passed to DAL, ie achieve a check before inserting a new row.

Mliya, this is something you are controlling at the database level, not at the application level.

If you are designing a database with a users table in which you would like to constraint the username and email columns to be UNIQUE you should create a UNIQUE INDEX on such columns.

without knowing your backend database (mySQL, SQL Server, MS Access, Oracle...) it's not the case to show you pictures or tell much more, just create the table with the designer and add these unique constraints to those columns and by design you will be sure no duplicated values will ever be inserted for username and email.

I also suggest you to create an ID column which would be set as PK (primary key, which means it will be automatically set as NON NULL and UNIQUE).

From your ASP.NET MVC application you should of course make sure that no duplicated values are then passed to the DAL for username and email. You could do this in different ways, the easiest is probably to check before inserting a new row if any user already exists with that username and/or email and if so you can show a notification message telling the user to please select another pair of values.

In an ASP.NET MVC architecture, you should try to do most of your validation in the Model, but with low-level validation rules like these, it's sometimes impossible. What you should look to for answers then is Domain-driven Design (DDD) where Application Services can solve such low-level needs.

Application Services will have access to the database (either directly, or better yet; indirectly through repositories ) and can perform low-level validation and throw ValidationException or something similar (with detailed information the Controller can act upon and respond to the user) when a prerequisite or business rule isn't met.

S#arp Architecture implementes all of this in a best-practice framework that you can use as a basis for your ASP.NET MVC applications. It is highly opinionated towards DDD principles and NHibernate, and it will sometimes force your hand on how you do stuff, which is kind of the point. The most important part about it is that it learns you how to deal with these kinds of problems.

To answer your question more concretely and in the spirit of DDD, this is how I would solve it:

public class UserController
{
    private readonly IUserService userService;

    public UserController(IUserService userService)
    {
        // The IUserService will be injected into the controller with
        // an "Inversion of Control" container like NInject, Castle Windsor
        // or StructureMap:
        this.userService = userService;
    }

    public ActionResult Save(UserFormModel userFormModel)
    {
        if (userFormModel.IsValid)
        {
            try
            {
                // Mapping can be performed by AutoMapper or some similar library
                UserDto userDto = Mapper.Map<UserDto>(userFormModel);
                this.userService.Save(userDto);
            }
            catch (ValidationException ve)
            {
                ViewBag.Error = ve.Detail;
            }
        }

        // Show validation errors or redirect to a "user saved" page.
    }
}

public class UserService : IUserService
{
    private readonly IUserRepository userRepository;

    public UserService(IUserRepository userRepository)
    {
        // The IUserRepository will be injected into the service with
        // an "Inversion of Control" container like NInject, Castle Windsor
        // or StructureMap:
        this.userRepository = userReposityr;
    }

    public UserDto Save(UserDto userDto)
    {
        using (this.userRepository.BeginTransaction())
        {
            if (!this.userRepository.IsUnique(userDto.UserName))
            {
                // The UserNameNotUniqueValidationException will inherit from ValidationException
                // and build a Detail object that contains information that can be presented to
                // a user.
                throw new UserNameNotUniqueValidationException(userDto.UserName);
            }

            userDto = this.userRepository.Save(userDto);
            this.userRepository.CommitTransaction();

            return userDto;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM