【问题标题】:How do I expose non persisted properties using a WCF Data Service?如何使用 WCF 数据服务公开非持久属性?
【发布时间】:2011-04-27 09:05:54
【问题描述】:

我使用 Entity Framework 4 创建了一个实体模型,我通过 WCF 数据服务公开了该模型。我的一个实体需要定义不持久保存到数据库的属性,但实体模型设计器不允许您这样做。

为了解决这个问题,我将我的所有对象都定义为 POCO 对象,这允许您将非持久属性添加到您的对象,但不能添加到您的模型。

我遇到的问题是,因为这些非持久化属性只存在于对象本身而不是模型中,所以它们不会通过 WCF 数据服务公开。

有没有办法在实体模型中定义不持久化到数据库的属性?

提前感谢您的任何回复

瑞恩

【问题讨论】:

    标签: c# wcf entity-framework


    【解决方案1】:

    模型的类是部分的。您可以在类的其他部分编写您的非持久属性。请写下这是否可行,因为我没有使用 WCF 数据服务,但每次我需要业务对象中未映射到数据库中字段的属性时,我都会这样做。

    【讨论】:

    • 不幸的是,这已经是我试图做的。但是,当您创建对 WCF 数据服务的服务引用时,这些属性不会出现在 Reference.cs 中。
    【解决方案2】:

    我认为 ikirachen 在使用部分类来定义附加属性方面走在正确的轨道上。为了让 WCF 公开它们,您还必须使用 DataMember 特性标记这些属性。我创建了一个小型 WCF 服务来对此进行测试:

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string DoStuff(User user);
    }
    
    public class Service1 : IService1
    {
        public string DoStuff(User user)
        {
            string result = string.Empty;
            foreach (Guid leadId in user.AssociatedLeadIds) 
            {
                // This is going to console on client,
                // just making sure we can read the data sent to us
                result += leadId.ToString() + "\n";
            }
    
            return result;
        }
    }
    
    // partial entity model class
    public partial class User
    {
        // This is not persisted to our DB with the user model
        [DataMember]
        public ICollection<Guid> AssociatedLeadIds { get; set; }
    }
    

    这是客户端代码,显示了通过 WCF 公开的 AssociatedLeadId:

    class Program
    {
        static void Main(string[] args)
        {
            User u = new User
            {
                // Here we set our non-persisted property data
                AssociatedLeadIds = new Guid[] 
                {
                    Guid.NewGuid(),
                    Guid.NewGuid(),
                    Guid.NewGuid()
                },
                // The rest are persisted properties
                ApplicationId = Guid.NewGuid(),
                UserName = "TestUser",
                LoweredUserName = "testuser",
                LastActivityDate = DateTime.Now,
                IsAnonymous = false
            };
    
            using (Service1Client svc = new Service1Client())
            {
                // Here we call the service operation 
                // and print the response to the console
                Console.WriteLine(svc.DoStuff(u));
            }
    
            Console.ReadKey();
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 进一步充实了代码。如果您仍然无法通过 WCF 公开属性,请告诉我。
    • 感谢您的输入 jlaneaz,不幸的是,这仍然不适用于使用 WCF 数据服务的我。我想我知道问题是什么。 Wcf 数据服务的服务引用似乎是从 EDMX 文件而不是代码库构建的,因此只有 EDMX 文件中存在的那些属性被序列化到服务引用中。
    猜你喜欢
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多