====================问题====================
首先,我使用的是实体框架(代码优先(。我有以下课程:
public class RandomObject
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order = 1)]
public int Id { get; protected set; }
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order = 2)]
public Guid UniqueId { get; protected set; }
public string Other { get; set; }
}
我还有一个迁移文件夹(包(,在其中我为数据库添加了一些对象。
private void AddDefaultObjects(Context context)
{
var object1 = new RandomObject{ Other = "qsdf1" };
var object2 = new RandomObject{ Other = "qsdf2" };
var object3 = new RandomObject{ Other = "qsdf3" };
var objects = new RandomObject[3]{object1 , object2 , object3 };
context.RandomObjects.AddOrUpdate(object => object.Id, objects);
context.SaveChanges();
}
但当我添加对象时,它们都会得到相同的UniqueId=>NOK(但不同的Id=>OK(
====================尝试次数====================
我尝试添加属性
[Index(IsUnique = true)]
或设置(在我的迁移配置文件中(
column.DefaultValueSql = "newid()";
====================结果====================
Id | UniqueId
--------------------------------------------
19 | db1e353e-7dd7-e311-8250-8c89a5c20da1
20 | dc1e353e-7dd7-e311-8250-8c89a5c20da1
21 | dd1e353e-7dd7-e311-8250-8c89a5c20da1
试试这个。。。。我认为您的AddOrUpdate
在第一个论点中需要复合主键的两个部分:
context.RandomObjects.AddOrUpdate(object =>
new { object.Id, object.UniqueId },
objects);