【问题标题】:How to access navigation properties in EF using repository pattern如何使用存储库模式访问 EF 中的导航属性
【发布时间】:2015-06-05 11:13:51
【问题描述】:

上下文:ASP.NET Web 应用程序

Base Repository(抽象类)实现了所有其他存储库继承所需的基本功能: IE。 -PersonRepo -AddressRepo

编辑: 您将查询多个数据库表的代码放在哪里,其中一些与相应存储库中的导航属性没有直接关系?

现在,访问导航属性的最佳方式是什么? 使用存储库模式时非常麻烦。 如果没有方便的解决方案,我会坚持使用旧的 DAL 层,里面包含所有内容,并直接使用 DbContext。

我刚刚想出了一个在我的 PersonRepository 实现中访问导航属性的临时解决方案:

public Person InsertNewPersonWithAddress(Person p, Address addr)
        {
            this.Insert(p); // insert person
            var ar = new AddressRepository(this.ctx);
            ar.Insert(addr);  // insert address
            this.Addresses(p).Add(addr);  // add address to person

            return p;
        }

        /* Navigation Properties */ 
        ICollection<Address> Addresses(Person p)
        {
            return ctx.Entry<Person>(p).Collection<Address>("Addresses").CurrentValue;
        }

Base Repository类实现如下接口

public interface IRepository<T> where T : class
    {
        IQueryable<T> All();
        IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
        T Insert(T entity);
        IEnumerable<T> InsertMultiple(IEnumerable<T> items);
        T Delete(T entity);
        IEnumerable<T> DeleteMultiple(IEnumerable<T> items);
        T Update(T entity);
        IEnumerable<T> UpdateMultiple(IEnumerable<T> items);
        void Save();
    }

数据库设计:

Person --> PersonAddress(联结表)

这个问题有什么智能解决方案吗?

【问题讨论】:

标签: c# entity-framework repository-pattern


【解决方案1】:

你想错了。导航属性是实体的属性,而不是存储库的属性。导航属性不需要实例化Repository,直接添加到Entity即可。

public Person InsertNewPersonWithAddress(Person p, Address addr)
{
    p.Address = addr;
    this.Insert(p); // insert person

    return p;
}

现在,如果您要插入新的 Person,但希望将其附加到现有的 Address(而不是插入两者的新副本),则可以将 AddressId FK 公开为 @987654325 上的属性@Entity,并传入FK 值来做链接。无论哪种情况,此存储库都不需要访问另一个存储库。

【讨论】:

  • 仅供参考,我想插入一个具有新地址的新人。断开连接的场景。我现在就试试你的方法..
  • 好的,这在这种情况下有效,我希望在所有其他情况下也一样 :-)。我在想我必须这样做:` //ctx.Persons.Attach(p); //ctx.Entry(p).State = System.Data.Entity.EntityState.Added; //ctx.Addresses.Attach(addr); //ctx.Entry
    (addr).State = System.Data.Entity.EntityState.Added; //p.Addresses.Add(addr);`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多