0
我遇到了LINQ到我已解決的實體問題,但希望確保以正確的方式解決問題。ASP.NET MVC類繼承和LINQ
我有2類:
namespace ShopTest.Models
{
public class Shop
{
public int ShopID { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postcode { get; set; }
public string Country { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude{ get; set; }
}
[NotMapped]
public class ShopLocation : Shop
{
public decimal AddressLatitude { get; set; }
public decimal AddressLongitude { get; set; }
public decimal DistanceFromAddress
{
get
{
return Convert.ToDecimal(
Math.Sqrt(
Math.Pow(Convert.ToDouble(this.Latitude - this.AddressLatitude), 2.0)
+
Math.Pow(Convert.ToDouble(this.Longitude- this.AddressLongitude), 2.0)
)
* 62.1371192
);
}
}
}
}
當LINQ查詢,我原來試過:
decimal lat = Convert.ToDecimal(-33.8736510, NumberFormatInfo.InvariantInfo);
decimal lng = Convert.ToDecimal(151.2068896, NumberFormatInfo.InvariantInfo);
var nearbyShops = from c in db.Shops
where Math.Abs(c.lat - lat) < 0.25M &&
Math.Abs(c.lng - lng) < 0.25M
select new NearbyShopLocation()
{
StoreNumber = store.StoreNumber,
Address = store.Address,
City = store.City,
Region = store.Region,
CountryCode = store.CountryCode,
PostalCode = store.PostalCode,
Latitude = store.Latitude,
Longitude = store.Longitude,
AddressLatitude = lat,
AddressLongitude = lng
};
var nearbySortedShops = nearbyShops.ToList().OrderBy(s => s.DistanceFromAddress).ToList();
但是我一直得到錯誤「實體或複雜類型「ShopTest.Controllers.Shops '不能構建一個LINQ to Entities查詢「
我已經解決了以下代碼的問題,但它沒有任何意義,爲什麼這將工作 - 對MVC是新的我希望有人可以探討就是它。 :-)
var nearbyShops = (from c in db.Shops
where Math.Abs(c.lat - lat) < 0.25M &&
Math.Abs(c.lng - lng) < 0.25M
select new
{
StoreNumber = c.StoreNumber,
Address = c.Address,
City = c.City,
Country = c.Country,
PostalCode = c.PostalCode,
Latitude = c.Latitude,
Longitude = c.Longitude,
}).ToList().Select(l => new ShopLocation
{
Name = l.Name,
City = l.City,
State = l.State,
Country = l.Country,
Lat = l.Lat,
Lng = l.Lng,
AddressLatitude = lat,
AddressLongitude = lng
}).ToList().OrderBy(s => s.DistanceFromAddress).ToList();
我這樣做是否正確?有沒有更好的辦法?
很大的反響,非常有幫助和教育,以及完美。謝謝! – 2012-04-25 08:25:15