1

是否有可能有一个主键和另一个不是主键的实体框架中的“自动增量”功能的字段?是否可以自动增加一个不是实体框架中主键的属性?

我发现这个在网络上,尝试过,但它不工作:

public int Id { get; set; } 

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
public int ImageId { get; set; } 

在这种情况下,ID始终为0

所以现在我又回到了这一点: Id是主键,我用MAX(Id) + 1递增ImageId整数。

更新:我甚至正在考虑为ImageId创建另一个表格。但我不确定这会不会是一个矫枉过正的问题。

+1

架构怎么样子? – abatishchev

+0

MSSQL架构?现在'Id'是主键,'ImageId'是一个整数。我无法弄清楚如何让'ImageId'字段自动增加其他的'MAX(Id)+ 1',我不知道这是不是一个好主意。 –

+0

MS SQL只允许每个表有一个标识列。 – afrazier

回答

1

我之前试过这个。 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 
+0

到目前为止,这看起来对我来说也是最好的解决方案......如果没有其他人会想出更好的解决方案,我会接受你的答案作为我的解决方案......会给它一两天。 –

0

乔的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. 
    } 
} 
+0

不知道我是否理解你的答案。所以你建议用c#做这一切? –

+1

其实,我刚看到你的编辑。如果你可以创建一个表,那就是我会做的。 –

相关问题