简体   繁体   English

表名作为主键的一部分

[英]Table name as part of primary key

I have an audit trailing system in my project from http://doddleaudit.codeplex.com/ . 我的项目中有一个来自http://doddleaudit.codeplex.com/的审核跟踪系统。 As you can see on this image it records the EntityTable - which is the table name, and the EntityTableKey - which is the primary key 如您在此图像上所看到的,它记录了EntityTable-这是表名,以及EntityTableKey-这是主键 在此处输入图片说明

I would like to associate the audit records with the tables it had recorder, then query the result in linq to sql. 我想审计记录与它有记录的表关联,然后在LINQ查询结果到SQL。 But the problem is if the audit table has record for orders and record for products it will never know just by the primary key, where does the record belong, thus i need to use the table name as part of the key. 但是问题是,如果审计表具有订单记录和产品记录,它将永远不会仅仅通过主键知道记录,该记录在哪里,因此我需要使用表名作为键的一部分。

So the question is: Is it possible to create a relation that will have a composite primary key that contains the table name in it? 因此,问题是:是否可以创建一个将具有包含表名的复合主键的关系?

AuditRecord to Orders
AuditRecord to Products

You could do it, but I would recommend a bit different approach. 您可以做到,但我建议您使用其他方法。

Don't use char/varchars/nvarchar in your PK/FK, it bloats the index. 不要在PK / FK中使用char / varchars / nvarchar,它会使索引膨胀。 I would rather create another table that will hold TableId/TableName pairs of all your tables (you can use sys.tables.object_id for your id if you wish) and have a FK in AuditRecords to it. 我宁愿创建另一个表来容纳所有表的TableId / TableName对(如果愿意,可以使用sys.tables.object_id作为ID),并在AuditRecords中添加FK。 Then establish composite key between AuditRecords and AuditRecordFields (Id, TableId). 然后在AuditRecords和AuditRecordFields(Id,TableId)之间建立复合键。

Another thing: 另一件事:

  • EntityTable and AssociationTable should be of sysname type EntityTable和AssociationTable应该为sysname类型
  • AuditDate can be of type Date (available from SQL Server 2008) AuditDate的类型可以为Date(可从SQL Server 2008获得)

EDIT: 编辑:

If you like to access audit records from each object, you can create a base class for your audited objects and implement following method (beware, it's untested): 如果您想从每个对象访问审核记录,则可以为审核对象创建基类并实现以下方法(请注意,未经测试):

public IQueryable<AuditRecord> AuditRecords
{
    get
    {
        MyContext ctx = new MyContext();

        var ars = from ar in ctx.AuditRecords
                  where ar.EntityTable.Equals(this.GetType().Name)
                  select ar;

        return ars;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM