entity framework 6 - check if record exists before insert and concurrency

前端 未结 3 1959
梦谈多话
梦谈多话 2020-12-19 04:54

I have the following scenario:

A business logic function that uses ef6 checks if a record already exists. If the record does not exists, it is inserted on the databa

3条回答
  •  青春惊慌失措
    2020-12-19 05:20

    I would harness the concurrency handling built into Entity Framework rather than write my own logic.

    You add a concurrency token to the database. Typically this would be a RowVersion field:

    Using FluentAPI:

    modelBuilder.Entity() 
        .Property(t => t.Timestamp) 
        .IsRowVersion(); 
    

    Using Data Annotations:

     [Timestamp]
     public byte[] RowVersion { get; set; }
    

    Typically you then handle the DbUpdateConcurrencyException thrown when there is a problem:

            using (var context = new SchoolDBEntities())
            {
                try
                {
                    context.Entry(student1WithUser2).State = EntityState.Modified;
                    context.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    Console.WriteLine("Optimistic Concurrency exception occured");
                }
            }
    

    References:

    Configuring a concurrency token

    Handling concurrency in Entity Framework

    Optimistic concurrency patterns using Entity Framework

    EDIT Just realised that I have misread your question. You aren't really talking about concurrency here, as your question title suggests. You just want to ensure that a record's natural key is unique. The way to do that is over here: https://stackoverflow.com/a/18736484/150342

提交回复
热议问题