繁体   English   中英

使用带有RIA Services的参数的计算属性

[英]Calculated Property using a Parameter with RIA Services

我正在执行地址之间的距离计算。 特别是用户与特定位置之间的距离。 我可以构建使数据库计算距离并按该距离对结果排序的LINQ查询。 但是,我找不到在实体中返回该距离的方法。 查询的简化版本如下:

    public IQueryable<Place> GetPlacesWithinRadiusOfUser(double userLongitude, double userLatitude, int miles )
    {

        return (from Place in this.ObjectContext.Places
                where RadiusOfEarth * Math.Acos((double)
                    (Math.Sin((double)Place.Addresses.First().Latitude / DegreesToRadians) * Math.Sin(userLatitude / DegreesToRadians))
                    +
                    (Math.Cos((double)Place.Addresses.First().Latitude / DegreesToRadians) * Math.Cos(userLatitude / DegreesToRadians)
                    * Math.Cos((userLongitude / DegreesToRadians) - ((double)Place.Addresses.First().Longitude / DegreesToRadians))
                    )
                    )
                    <= miles
                select Place);


    }

从本质上讲,我需要从上面的数学作为地址实体 (它是Place的子代)上的Distance属性返回。 我创建了以下部分类,并且该字段确实出现在silverlight客户端中。

public partial class Address
{
    //The Distance field is used to return a distance if a reference point is provided in a query
    [DataMember]
    public Nullable<decimal> Distance { get; set; }

}

因此, Distance属性和计算取决于GetPlacesWithinRadiusOfUser方法的参数。

有没有一种方法可以将参数从查询中获取到地址实体,以便我可以执行相同的计算,并在到达客户端时在实体中使用它?

我当然可以创建一个客户端例程来执行此计算,但是这会变得很混乱,因为我将不得不在需要它的每个UI中不断注入该例程。 我更希望在Entity中返回它,以便我可以绑定到它并显示它(本质上我希望从SQL返回一个计算字段)。 如果它是条条框框的SQL,那将是微不足道的,但是我对如何使用RIA Services和Entity Framework做到这一点感到困惑。

还有想法吗?

有了Entity Framework,我再也找不到一种真正做到这一点的方法(我想要的方法)。 但是,我找到了一个很好的解决方案。 步骤如下:

  1. 通过在ObjectContext上进行距离计算来创建查询。...然后通过返回的值过滤Place查询。 所有这些都是在客户端的一次查询调用中完成的。 它不会返回距离...但是我以不同的方式处理。

  2. 然后,我在所有相关对象上创建了扩展方法,如下所示:

     public static class AddressExtensions { public static double CalculateDistanceTo(this Address address1, double longitude, double latitude) { if (address1 == null) { return 0; } return Global.CalculateDistance((double?)address1.Longitude, (double?)address1.Latitude, longitude, latitude); } public static double CalculateDistanceTo(this Address address1, Address address) { if (address1 == null || address == null) { return 0; } return Global.CalculateDistance((double?)address1.Longitude, (double?)address1.Latitude, (double?)address.Longitude, (double?)address.Latitude); } public static double CalculateDistanceTo(this Address address1, User user) { if (address1 == null) { return 0; } return address1.CalculateDistanceTo(user.Addresses.FirstOrDefault()); } public static double CalculateDistanceTo(this Address address1, Place place) { if (address1 == null) { return 0; } return address1.CalculateDistanceTo(place.Addresses.FirstOrDefault()); } } 
  3. 然后,在需要获取距离的任何地方,我都可以执行类似User.DistanceTo(myAddress)的操作

这实际上要好一些,因为无论什么情况我都可以重用相同的扩展方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM