#wcf #web-services #linq-to-sql
#wcf #веб-службы #linq-to-sql
Вопрос:
Я использую linq to SQL в качестве своего ORM, а затем передаю объекты linq To Sql через веб-службу на мои страницы пользовательского интерфейса aspx.
Это работает нормально, когда я передаю напрямую Linq к объектам sql, они сериализуются, и я могу получить к ним доступ как json. И этот веб-сервис также отлично работает, когда я передаю poco DTO, поскольку некоторые данные в этих объектах поступают из нескольких разных классов linq to SQL.
Проблема, с которой я сталкиваюсь, заключается в том, что я пытаюсь использовать класс linq to SQL с дополнительными полями, определенными в пользовательском частичном классе. Поля в моей пользовательской части частичного класса не передаются через веб-службу, поля в сгенерированной linq to sql части частичного класса встречаются.
Поля присутствуют при создании объекта, и я вижу их в отладчике Visual Studio до тех пор, пока они не перейдут через службу, но их нет в json на другой стороне.
Вот частичный класс
using System.Runtime.Serialization;
namespace GPSO.ATOMWebDataLayer.LinqToSql
{
public partial class Geofence
{
public string FillColor { get; set; }
}
}
Вот веб-служба
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Xml;
using GPSO.ATOMWebBusinessLayer;
using GPSO.ATOMWebDataLayer;
using GPSO.ATOMWebDataLayer.LinqToSql;
using GPSO.ATOMWebDataLayer.Objects;
using GPSOnline.ReportWebService;
using Contact = GPSO.ATOMWebDataLayer.LinqToSql.Contact;
using Event = GPSO.ATOMWebBusinessLayer.Event;
using Geofence = GPSO.ATOMWebBusinessLayer.Geofence;
namespace GPSOnline
{
[ServiceContract(Namespace = "GPSOnline")]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ATOMWebService
{
private string _atomDbConnectionString;
private string _aspNetDbConnectionString;
private string _satelliteDbConnectionString;
[OperationContract]
[WebGet]
public IEnumerable<GPSO.ATOMWebDataLayer.LinqToSql.Geofence> GetAllGeofences()
{
NoCache();
var geofenceRepo = new GeofenceRepository(GetConnectionString());
return geofenceRepo.GetAllGeofences().ToList();
}
}
}
and here is the Repository
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using GPSO.ATOMWebBusinessLayer;
using GPSO.ATOMWebDataLayer.LinqToSql;
using GPSO.MapUtilities;
using GPSO.Repository;
using Microsoft.SqlServer.Types;
using Geofence = GPSO.ATOMWebBusinessLayer.Geofence;
namespace GPSO.ATOMWebDataLayer
{
public class GeofenceRepository
{
private static string _connectionString = "";
public GeofenceRepository(string connectionString)
{
_connectionString = connectionString;
}
public IEnumerable<LinqToSql.Geofence> GetAllGeofences()
{
var dataContext = new AtomWebDataContext(_connectionString);
return allGeofences = dataContext.Geofences.ToList();
}
}
и вот страница пользовательского интерфейса
<%@ Page Language="C#" MasterPageFile="~/Private/ATOMWEB.master" AutoEventWireup="true"
Async="true" Inherits="GPSOnline.Assets" Title="ATOM®web Asset Map" CodeBehind="Assets.aspx.cs" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register Src="../UserControls/ucAssetPicker_ClientEvent.ascx" TagName="ucAssetPicker"
TagPrefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderLeft" runat="Server">
<asp:ScriptManagerProxy ID="ScriptManagerProxy" runat="server">
<Services>
<asp:ServiceReference Path="/ATOMWEBService.svc" />
</Services>
<Scripts>
<asp:ScriptReference Path="http://maps.google.com/maps?file=apiamp;amp;v=2amp;amp;sensor=trueamp;amp;client=gme-gpsonline" />
<asp:ScriptReference Path="~/scripts/MapPanel.js" />
<asp:ScriptReference Path="~/scripts/jquery-1.3.2.min.js" />
<asp:ScriptReference Path="~/scripts/AssetLabel.js" />
<asp:ScriptReference Path="~/scripts/NumberFormatting.js" />
<asp:ScriptReference Path="~/scripts/DateFormatting.js" />
<asp:ScriptReference Path="~/scripts/Utilities.js" />
<asp:ScriptReference Path="~/scripts/geofences.js" />
<asp:ScriptReference Path="~/scripts/mapUtilities.js" />
</Scripts>
</asp:ScriptManagerProxy>
<script type="text/javascript">
var map = null,
atomWebServiceProxy = null,
selectedAssetId = null,
userPreferences = null,
userId = null,
assets = [],
assetMarkers = [],
updatedAssets = [],
assetStatusPanel = null,
assetContextItem = null,
trackAsset = false,
firstTime = true,
deviceChannels = { },
assetPanelLayouts = { },
geoFences = { };
function contentPageLoad() {
atomWebServiceProxy = new GPSOnline.ATOMWebService();
}
/// <summary>
/// <summary>
/// calls the webservice to get all the geo fences.
/// Runs gotGeoFences when service call successfull
/// </summary>
function getGeofences() {
atomWebServiceProxy.GetAllGeofences(gotGeofences);
}
/// <summary>
/// Add the collection of geoFences to the page
/// </summary>
/// <param name="Result"> A collection of GeoFences </param>
function gotGeofences(result) {
geoFences = new GeoFencesObj(map, result, "chkToggleGeofences", "<%=RadContextMenuGotoGeofence.ClientID%>", !userPreferences.DefaultShowGeofences);
if (userPreferences.DefaultLocationType == 2 amp;amp; userPreferences.HomeSiteId != null) {
geoFences.zoomToGeofence(userPreferences.HomeSiteId);
}
}
}
Ответ №1:
Вам необходимо использовать [DataMemberAttribute]
:
namespace GPSO.ATOMWebDataLayer.LinqToSql
{
[DataMember]
public partial class Geofence
{
public string FillColor { get; set; }
}
}
Комментарии:
1. Спасибо за это, да, я пробовал это. Но я получаю сообщение об ошибке на странице. Я прикрепил снимок экрана из firebug.
2. Серьезно, вы не могли скопировать и вставить текст? Это ошибка сервера. Сервер выдал необработанное исключение. Посмотрите в журнале событий приложения.
3. Да, не беспокойтесь, я заглянул в журнал, и в частичном классе было еще одно поле, которое я опустил для краткости, в котором не было метода установки. Получается, что все поля должны иметь как получатели, так и установщики.
4. Для потомков его сообщение об ошибке было «Ошибка внутреннего сервера NetworkError: 500 — localhost: 52360/ATOMWEBService.svc/jsdebug »