【问题标题】:Is it possible to auto increment a property which is not the primary key in Entity Framework?是否可以自动增加不是实体框架中主键的属性?
【发布时间】:2015-10-23 18:45:58
【问题描述】:

Entity Framework 中的“自增”功能是否可以有一个主键和另一个不是主键的字段?

我在网上找到了这个,试过了,但是不行:

public int Id { get; set; }

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

在这种情况下,Id 始终为 0。

所以现在我回到这个:Id 是主键,我使用MAX(Id) + 1 来增加ImageId 整数。

更新:我什至想为ImageId 创建另一个表。但我不确定这是否是矫枉过正。

【问题讨论】:

  • 架构是什么样子的?
  • MSSQL 架构?现在Id 是主键,ImageId 是一个整数。我不知道如何使ImageId 字段自动递增,而不是MAX(Id) + 1,我不知道这是否是个好主意。
  • MS SQL 只允许每个表有一个标识列。
  • @afrazier 我知道...我只是想列出我已经尝试过的内容,以免它成为答案,因为我已经知道它无法解决问题。
  • 我会在插入触发器之后使用,或者让它只是插入/更新的一部分。或者更好 - 一个微服务来跟踪它。

标签: c# sql-server entity-framework ef-code-first identity-column


【解决方案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

【讨论】:

  • 到目前为止,这对我来说也是最好的解决方案...如果没有其他人会提出更好的解决方案,我会接受您的回答作为我的解决方案...给它一天或两个。
【解决方案2】:

乔斯莫,

试试这个:

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.
    }
}

【讨论】:

  • 不知道我是否理解你的回答。所以你建议用c#来做这一切?
  • 其实我刚看到你的编辑。如果你可以创建一个表,这就是我会做的。
猜你喜欢
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
相关资源
最近更新 更多