2010-10-07 130 views
0

我们有两个具有相同列的实体,但实体名称不同。我可以使用第一个实体实例创建2个实体吗?实体框架4.0。实体创建

我们尝试过.AddObject(“Entity2 name”,entityOneinstance)但它失败。

请建议这是可能的或任何其他方法。

在此先感谢

回答

0

由于实体类型是不同的,你的添加操作将下降是肯定的。

你会需要一个映射器或(显式/隐式)转换运算符在我认为你的实体类型之间。

要清楚,对于谈话的解决方案,假设你有Entity1Entity2并且都具有的特性,PropertyProperty_1Property_2Property_3。我假设你有默认的代码生成策略(不是POCO或者是)。然后你就可以添加部分ENTITY2和ENTITY1班,隐式转换算子,例如:

public partial class Entity2 
{ 
    public static implicit operator Entity2(Entity1 entity1) 
    { 
     return new Entity2() 
     { 
      Property = entity1.Property, 
      Property_1 = entity1.Property_1, 
      Property_2 = entity1.Property_2, 
      Property_3 = entity1.Property_3 
     }; 
    } 
} 

所以,你现在可以做的:

using (var provider = new Model1Container12()) 
{ 
    Entity1 entity1 = new Entity1(); 
    provider.AddObject(provider.Entity2Set.Name, entity1); 
    // or 
    provider.AddToEntity2Set(entity1); 
} 

转换将被隐式地为你转换操作符定义定义。

我不知道Entity Framework本身是否有解决方案,但转换看起来像是我的解决方案。或者你也可以使用AutoMapper类的东西。我没有这方面的详细信息。

+0

意味着我必须为每一个单独的实体实例?任何一个实体都不能被重新用于添加另一个实体到数据库表中?请澄清。 – Aaron 2010-10-07 09:59:21

+0

我想你需要创建一个你想添加到实体上下文中的类型实例。我已经更新了我的答案。希望能有所帮助。如果答案不明确,请通知我,或者我误解了这种情况。 – 2010-10-07 11:12:01

0

在EF4,对象集被引入,这是有点漂亮..

我的做法会使用存储库模式...

首先创建一个抽象基类..

public abstract class BaseRepository<T> where T : class 
{ 
    #region Members 

    protected IObjectSet<T> _objectSet; 

    #endregion 

    #region Ctor 

    public BaseRepository(ObjectContext context) 
    { 
     _objectSet = context.CreateObjectSet<T>(); 
    } 

    #endregion 

    #region Methods 

    public void Add(T entity) 
    { 
     _objectSet.AddObject(entity); 
    } 

    public IEnumerable<T> GetAll() 
    { 
     return _objectSet; 
    } 

    #endregion 
} 

然后为每个需要访问的表格创建派生类。

示例(接口和实现): 生产者是ta传播POCO对象。

接口:

public interface IProducerRepository 
{ 
    Producer GetById(int id); 
    void Add(Producer entity); 
    IEnumerable<Producer> GetAll(); 
} 

实现:

public class ProducerRepository : BaseRepository<Producer>, IProducerRepository 
{ 
    #region Ctor 

    public ProducerRepository(ObjectContext context) : base(context) 
    { 
    } 

    #endregion 

    #region Methods 

    public Producer GetById(int id) 
    { 
     return _objectSet.SingleOrDefault(e => e.Id == id); 
    } 


    #endregion 
} 

希望这有助于.. :-)