Home > Software design >  Entity Framework Core: How Can I update Entity no duplicate values?
Entity Framework Core: How Can I update Entity no duplicate values?

Time:06-11

I have a student table that has three fields.

1.ID. is PK 2.No. just like student number 3.Name. student Name

when I use EF core to update student name. I need to make sure that the student name and student number are not duplicated

This is my method

// get same name student
var currenItem = await _context.TLibInfo.FirstOrDefaultAsync(v => v.name== item.name);
// check if current is null I can update
if (currenItem == null)
{
// get student by number
 var existItem = await _context.TLibInfo.FirstOrDefaultAsync(v => v.no == item.no);
 if (existItem != null)
 {
    // then update
 }
}               

Is there a better way for me not to query twice?

For example It is not insert. It is update. just like I have 2 record.

id:1 name: davis number: A

id: 2 name: Jack number: B

I want to update id:2 record.

I want to make sure that when I update name, the name is not davis

CodePudding user response:

First of all, You could use one query to do that:

var student = await _context.TLibInfo.FirstOrDefaultAsync(s => s.name != item.name && s.no == item.no);
if (student != null)
{
    //update
}

BUT

If you need to have such behavior it would be useful to define a unique index on your database model. More detailed info here. In this Microsoft article, you will find information on how to create an index on the property, but your goal would be to create a unique index on two properties of the Student entity - Name and number.

CodePudding user response:

You can use the following query:

var students = await _context.TLibInfo
    .Where(s => s.no == item.no || s.name == item.name && s.no != item.no)
    .ToListAsync();

if (students.Count == 0)
{
   // nothing to update
}
else if (students.Count > 1)
{
    // another student with given name already exists
}
else 
{
    var student = students[0];
    student.name = item.name;

    await _context.SaveChangesasync();
}

But this do not guarantee consistency when another user is also trying to change name for the student at the same time. So better, to start transaction and add Unique constraint on the Name column.

  • Related