The context is each Car
has a corresponding CarBrand
. Now my classes are as shown below:
public class Car
{
public int CarId { get; set; }
public int CarBrandId { get; set; }
public CarBrand CarBrand { get; set; }
}
public class CarBrand
{
public int CarBrandId { get; set; }
public string Name { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<CarBrand> CarBrands { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(@"Data Source = MyDatabase.sqlite");
}
}
Here's a sample execution of my code...
class Program
{
static void Main(string[] args)
{
AlwaysCreateNewDatabase();
//1st transaction
using (var context = new MyContext())
{
var honda = new CarBrand() { Name = "Honda" };
var car1 = new Car() { CarBrand = honda };
context.Cars.Add(car1);
context.SaveChanges();
}
//2nd transaction
using (var context = new MyContext())
{
var honda = GetCarBrand(1);
var car2 = new Car() { CarBrand = honda };
context.Cars.Add(car2);
context.SaveChanges(); // exception happens here...
}
}
static void AlwaysCreateNewDatabase()
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
}
static CarBrand GetCarBrand(int Id)
{
using (var context = new MyContext())
{
return context.CarBrands.Find(Id);
}
}
}
The problem is I get 'UNIQUE constraint failed: CarBrands.CarBrandId' exception when car2
is being added to the database with the same CarBrand
honda
.
What I expect it to do is during 2nd transaction's context.SaveChanges()
, it will add car2
and set it's relationship with CarBrand
appropriately but I get an exception instead.
EDIT: I really need to get my CarBrand instance in a different context/transaction.
//really need to get CarBrand instance from different context/transaction
CarBrand hondaDb = null;
using (var context = new MyContext())
{
hondaDb = context.CarBrands.First(x => x.Name == "Honda");
}
//2nd transaction
using (var context = new MyContext())
{
var car2 = new Car() { CarBrand = hondaDb };
context.Cars.Add(car2);
context.SaveChanges(); // exception happens here...
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…