如何确保代码内的列值唯一?

发布于 2024-12-02 23:19:22 字数 278 浏览 1 评论 0原文

我正在学习 ASP.NET MVC,并且对如何确保表的列(用户名和电子邮件)的唯一值感到困惑。

任何人都可以帮助我提供示例代码或显示 & 的教程链接吗?解释一下这个?

编辑:

我知道我可以在表列上应用唯一的键约束并实现它。但是,我想知道如何通过 ASP.NET MVC 代码实现它?

更新:

我希望在我的应用程序中进行检查,以便没有重复的值传递到 DAL,即在插入新行之前进行检查。

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, i.e. achieve a check before inserting a new row.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恍梦境° 2024-12-09 23:19:22

Mliya,这是您在数据库级别控制的东西,而不是在应用程序级别。

如果您正在设计一个包含 users 表的数据库,并且希望将其中的 usernameemail 列限制为 UNIQUE< /code> 您应该在此类列上创建一个唯一索引。

在不知道您的后端数据库(mySQL、SQL Server、MS Access、Oracle ...)的情况下,无法向您展示图片或告诉您更多信息,只需与设计器一起创建表,然后按设计将这些独特的约束添加到这些列您将确保不会为用户名和电子邮件插入重复的值。

我还建议您创建一个 ID 列,将其设置为 PK(主键,这意味着它将自动设置为 NON NULL 和 UNIQUE)。

在您的 ASP.NET MVC 应用程序中,您当然应该确保没有重复的值传递到用户名和电子邮件的 DAL。您可以通过不同的方式执行此操作,最简单的可能是在插入新行之前检查是否已存在使用该用户名和/或电子邮件的用户,如果是,您可以显示一条通知消息,告诉用户请选择另一对值。

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.

有木有妳兜一样 2024-12-09 23:19:22

在 ASP.NET MVC 架构中,您应该尝试在模型中完成大部分验证,但对于像这样的低级验证规则,有时这是不可能的。那么您应该寻找答案的是领域驱动设计(DDD),其中 应用服务可以解决这样的底层需求。

应用程序服务将有权访问数据库(直接访问,或者更好;通过 存储库),并且可以执行低级验证并抛出 ValidationException 或类似的东西(带有 Controller 可以采取行动的详细信息,并且当不满足先决条件或业务规则时响应用户)。

S#arp Architecture 在最佳实践框架中实现所有这些,您可以将其用作 ASP 的基础.NET MVC 应用程序。它对 DDD 原则和 NHibernate 有很强的固执,有时它会迫使你决定如何做事,这就是重点。它最重要的部分是它学习如何处理此类问题。

为了更具体地并本着 DDD 的精神回答你的问题,我将这样解决它:

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;
        }
    }
}

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;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文