2

我正在开发一个软件,其中有一些实体,例如:

public class Workspace
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual List<Playground> Playground { get; set; }
        public virtual List<Workspace> Children { get; set; }
        public virtual List<Member> Members { get; set; }

        public virtual Workspace Parent { get; set; }
    }   

public class Playground
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual List<Service> Services { get; set; }

        public virtual Workspace Workspace { get; set; }
    }

public class Service
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual Playground Playground { get; set; }
    }

这些是我的 EF4 POCO 对象。我正在使用存储库模式和以下界面:

public interface IRepository<T>
{
    void Add(T entity);
    void Delete(T entity);
    IEnumerable<T> Get(Expression<Func<T, bool>> expression);
    IEnumerable<T> Get();
    void Attach(T entity);

    int Save();
}

存储库有一个内部 ObjectContext。我有一个 UnitOfWork 包含我的存储库的实例,并负责保存对它们所做的更改。

到目前为止我做得对吗?

我正在实现这样的业务逻辑层:

public class DomainWorkspaceService : DomainServiceBase
    {

        public DomainWorkspaceService(Workspace workspace)
            : base(UnitOfWorkFactory.GetInstance())
        {
        }

        public void Create(Workspace workspace)
        {
            UoW.GetRepository<Workspace>().Add(workspace);
        }

        public void Delete(Workspace workspace)
        {
            var pservice = new DomainPlaygroundService();
            foreach (var playground in workspace.Playground)
                pservice.Delete(playground);

            foreach (var child in workspace.Children)
                Delete(child);
        }

    }

现在我不确定我是否朝着正确的方向前进。我的 POCO (将)负责验证,并使我能够做类似的事情

SomeWorkspace.Children.Add(new Workspace {...});

由于这些对象与上下文相关联,当我保存它们时,对集合的更改是否也会保存在数据库中?

另外,我希望我的 Playgrounds 不能在没有 Workspace 的情况下创建,而 Services 则不能在没有 Playground 的情况下创建。我应该在哪里创建和删除它们?

谢谢。

4

1 回答 1

1

到现在为止还挺好。

您可能希望将您的Save方法从存储库移到工作单元上。在实体框架中,您必须一次保存上下文中的所有更改;您不能按类型执行此操作。将它放在存储库上意味着只会保存对存储库的更改,这可能是不正确的。

您可能希望将工作区到操场的级联实现为数据库级联(实体框架将识别和支持),而不是手动对其进行编码。

是的,保存对上下文的更改将保存所有跟踪的更改,包括相关对象。

Regarding adding, if you don't expose the ObjectContext, then the only way that anyone will be able to add a Playground is via relationships with the objects you do expose.

于 2010-08-24T18:55:32.550 回答