代码之家  ›  专栏  ›  技术社区  ›  Jonathan Walton

我应该如何将子实体标记为“非活动”,而不是从数据库中删除,但它们的行为应该相同?

  •  1
  • Jonathan Walton  · 技术社区  · 9 年前

    我正在使用Code First,并且有如下实体:

    public class Account 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public int ContactId { get; set; }
        public virtual ICollection<Contact> Contacts { get; set; }
    }
    
    public class Contact 
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    从帐户中删除联系人时,我会从数据库中删除该行。现在,我们没有删除该行,而是将状态列更新为“非活动”。在这里,我向Contact实体添加了Status属性:

    public class Contact 
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public ContactStatus Status {g et; set; }
    }
    
    public enum ContactStatus 
    {
        Active = 0,
        Inactive = 1
    }
    

    非活动联系人的行为应类似于从数据库中删除的联系人。网站用户将删除该联系人,该联系人将像以前一样“消失”。

    这是我们当前的解决方案。我们创建了另一个名为ActiveContacts的属性:

    public class Account 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public int ContactId { get; set; }
        public virtual ICollection<Contact> Contacts { get; set; }
    
        [NotMapped]
        public ICollection<Contact> ActiveContacts
        { 
            get 
            {
                return Contacts.Where(c => c.Status == Status.Active).ToList();
            }
        }
    }
    

    这方面有一些问题。业务逻辑和linq查询不知道新的Status属性。然后我搜索所有代码以查找对旧属性Contacts的引用。有没有比将Contacts的所有引用更改为ActiveContacts更好的解决方案?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Jonathan Walton    9 年前

    这是我能想到的最好的东西。请随意指出此方法可能出现的任何缺陷或陷阱。

    我重命名了导航属性ContactsCollection,并使用InversePropertyAttribute维护对数据库中原始集合的引用。Contacts属性现在返回状态为Active的Contacts列表。

    public class Account 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public int ContactId { get; set; }
    
        [InverseProperty("Contact")]
        public virtual ICollection<Contact> ContactsCollection { get; set; }
    
        /// <summary>
        /// Represents a list of all Contacts with an Active Status
        /// </summary>
        [NotMapped]
        public ICollection<Contact> Contacts
        { 
            get 
            {
                return ContactsCollection.Where(c => c.Status == Status.Active).ToList();
            }
        }
    }
    

    现在,我不必搜索代码库,也不必用另一个名称重命名Contacts的属性。

    每当试图将新的“仅获取联系人”属性分配或添加到其中时,我也会遇到编译错误。我从未在非编译的razer视图中分配或添加集合。到目前为止,这种方法效果很好。