WCF KnownType输入实体框架

时间:2014-06-06 20:02:16

标签: c# wcf

我正在尝试设计一个使用Derived类的Knowntype属性的Web服务。

我使用knowtype的原因是为所有派生类都有一个端点。

[DataContract]
[KnownType(typeof(Derived))]
[KnownType(typeof(DerivedTwo))]
//And other derived types
class Base 
{
  string Name {get; set;}
}
[DataContract]
class Derived :Base
{
 string WorkedOn {get; set;}
}
[DataContract]
class DerivedTwo :Base
{
 string CompletedOn {get; set;}
}

public class TestContext :DbContext
{
  //ctor of context 

  public Dbset<Base> Base {get; set;}
  public Dbset<Derived> Base {get; set;}
}

public class Repository<T> where T:Base 
    {
        private readonly TestContext _testContext;
        public Repository()
        {
            _testContext = new TestContext();
        }

        public void Add(T input)
        {
           var kew =  _testContext.Set<T>().Add(input);
        }

        public void Save()
        {
            _testContext.SaveChanges();
        }  
}

public Interface IService 
{
  [OperationContract]
  void Add(Base base);
}

public class Service :IService
{
   public void Add(Base base)
   {
     var repository = new Repository<typeof(base)>();
     repository.Add(base);
     repository.Save();
   }
}

当客户端调用此端点并传递派生类时 我想要一个条目添加到派生类表(TPC - 具体类的表) 这甚至可能吗? 我的魔药是什么设计这样的网络服务。

已编辑回答


我很新,我不知道我应该在哪里回复,下面评论的编辑时间到期了,所以我在这里做。

我尝试了你的建议,EF将Base类中的属性插入到Base类表中,并从派生类插入到相应的表中。有什么方法可以强制它将所有数据插入到派生表中。

EDIT2 我在谷歌的帮助下找到答案我需要在DbSet上使用MapInheritedProperties。 谢谢你的帮助我将标记为已回答

1 个答案:

答案 0 :(得分:0)

您现有代码唯一的错误是var repository = new Repository<typeof(base)>();不是封闭通用的有效形式。

根据您所展示的内容,您的存储库类的设计是可疑的 - 它将更有意义地实现为

public class Repository 
{
    private readonly TestContext _testContext;
    public Repository()
    {
        _testContext = new TestContext();
    }

    public void Add<T>(T input) where T : Base
    {
       var kew =  _testContext.Set<T>().Add(input);
    }

    public void Save()
    {
        _testContext.SaveChanges();
    }  
}

这将允许您的服务实施

public void Add(Base input)
{
    var repository = new Repository();
    repository.Add(input);
    repository.Save();
}

按预期工作。

相关问题