Search code examples
c#wcfentity-frameworkdto

Why Entity Framework one to one relationship in WCF client-side is null?


i use Entity Framework one to one relationship in WCF server-side,Main code is:

[DataContract]
public class AppType
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [DataMember]
    public int TypeID { get; set; }

    [DataMember]
    public string TypeName { get; set; }
}

[DataContract]
public class App
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [DataMember]
    public long AID { get; set; }

    [DataMember]
    [ForeignKey("AppType")]
    public int TypeID { get; set; }

    [DataMember]
    public DateTime DateAdded { get; set; }

    [DataMember]
    public virtual AppType AppType { get; set; }
    //...
}

Because the Serialize Problem,i must close lazyloading and proxyclass in EF:

this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;

Now,the WCF Client-side can work,but i can't get "AppType" by "App": enter image description here

the GetAppByTypeidContentid method is:

public App GetAppByTypeidContentid(string contentid, int typeid)
{
    using (var db = new TagDbContext())
    {
        try
        {
            var app = db.Apps.SingleOrDefault(a => a.ContentID.Trim() == contentid.Trim() && a.TypeID == typeid);
            if (app != null)
            {
                return app;
            }
            else
            {
                throw new Exception("App not exist!");
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

Is must use DTO or not? who can help me?thanks


Solution

  • You turned off lazy loading so you must tell EF to load AppType:

    var app = db.Apps.Include("AppType")
                .SingleOrDefault(a => a.ContentID.Trim() == contentid.Trim() && a.TypeID == typeid);