简体   繁体   中英

Prevent posting of object if combination of unique fields already exist in a record with Entity Framework (DB First) (ASP.NET MVC)

If I have a an object as follows:

var example = new Example
{
    SomeName = viewModel.SomeName,
    SomeTitle = viewModel.SomeTitle,
    SomeAddress = viewModel.SomeAddress,
    SomeCity = viewModel.SomeCity
};

_class.AddObject(example);

The AddObject method uses an Add entity method from a repository. The domain upon which the view model is based has been generated by Entity Framework (6), DB first.

I'm currently trying ensure that the example object can not be posted unless it has a unique SomeName , SomeAddress and SomeCity . If a record already exists in the database with the same combination of those three fields, I'll show the user an error message.

Is there a built in way to do this in Entity Framework? Since the domain model has been auto-generated, I know that I can't annotate the properties there. I'm not sure if there's something I can do in the view model, or it's best to write some custom logic.

Thank you for your help!

You can use LINQ to check if the register already exists in the database prior insert a new record.

To make things easier and don't load anything unwanted in memory you can use Any() method along a lambda expression to query the database. This method will return true if any record with the provided filter is found or false if not.

bool recordExists = _myContext.MyTable.Any(x => x.SomeName == viewModel.SomeName && 
                                                x.SomeAddress == viewModel.SomeAddress && 
                                                x.SomeCity == viewModel.SomeCity)

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