[英]Is it possible to auto increment a property which is not the primary key in Entity Framework?
是否可以在Entity Framework中使用“自动增量”功能来拥有一个主键和另一个不是主键的字段?
我在网上找到了这个,并尝试了一下,但是没有用:
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ImageId { get; set; }
在这种情况下,Id始终为0。
所以现在我回到这一点: Id
是主键,我使用MAX(Id) + 1
来递增ImageId
整数。
更新:我什至在考虑为ImageId
创建另一个表。 但是我不确定这是否会造成过度杀伤。
我前一段时间试过了。 MSSQL确实支持它。 EF内存也不允许定义。
我的解决方案:我创建了一个辅助表,称为IDPool。 唯一目的是生成唯一的ID序列。 我在主表中使用了该值。 在这种情况下,我也可以使用GUID。 否则Guid是明显的替代方案。
编辑:提示为使事情更容易/更安全,请并行使用第二个上下文。 第二个上下文用于获取ID,您可以提交而不必担心会干扰主上下文中的当前更新。
var miniRep = luw.GetRepositoryMini<IdPool>(); // mini context managed here.
var nextrec = new IdPool()
miniRep.Add(nextrec);
miniRep.SaveChanges();
return nextrec.Id
Jo Smo,
尝试这个:
public static class ID
{
// Enumeration for parameter in NewID() method.
public enum Type { Customer, Vendor, Product, Transaction };
}
public class MyClass
{
// Variables hold the last ID. This will need to be serialized
// into your database.
public int lastCustomerID;
public int lastVendorID;
public int lastProductID;
public int lastTransactionID;
// Updates last-ID variable and returns its value.
public int NewID(ID.Type type)
{
switch (type)
{
case ID.Type.Customer:
lastCustomerID++;
return lastCustomerID;
case ID.Type.Vendor:
lastVendorID++;
return lastVendorID;
case ID.Type.Product:
lastProductID++;
return lastProductID;
case ID.Type.Transaction:
lastTransactionID++;
return lastTransactionID;
default:
throw new ArgumentException("An invalid type was passed: " + type);
}
}
private void AnyMethod()
{
// Generate new customer ID for new customer.
int newCustomerID = NewID(ID.Type.Customer);
// Now the ID is in a variable, and your last-ID variable is updated.
// Be sure to serialize this data into your database, and deserialize
// it when creating new instances.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.