Aplicativos de várias camadas usando L2S, WCF e classe base
-
27-09-2019 - |
Pergunta
Um dia, decidi criar este bom aplicativo de várias camadas usando L2S e WCF. O modelo simplificado é: banco de dados-> l2s-> wrapper (dto)-> aplicativo cliente. A comunicação entre cliente e banco de dados é alcançada usando objetos de transferência de dados que contêm objetos de entidade como suas propriedades.
abstract public class BaseObject
{
public virtual IccSystem.iccObjectTypes ObjectICC_Type
{
get { return IccSystem.iccObjectTypes.unknownType; }
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "BigInt NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
[global::System.Runtime.Serialization.DataMemberAttribute(Order = 1)]
public virtual long ID
{
//get;
//set;
get
{
return _ID;
}
set
{
_ID = value;
}
}
}
[DataContract]
public class BaseObjectWrapper<T> where T : BaseObject
{
#region Fields
private T _DBObject;
#endregion
#region Properties
[DataMember]
public T Entity
{
get { return _DBObject; }
set { _DBObject = value; }
}
#endregion
}
Muito simples, não é? Aqui está o problema. Cada uma das classes mapeadas contém a própria propriedade de identificação, então eu decidi substituí -la assim
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Divisions")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Division : INotifyPropertyChanging, INotifyPropertyChanged
{
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=1)]
public override long ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
}
O invólucro para a divisão também é bem direto:
public class DivisionWrapper : BaseObjectWrapper<Division>
{
}
Funcionou muito bem, desde que eu tenha mantido os valores de identificação na classe mapeada e sua classe BaseObject da mesma forma (isso não é uma abordagem muito boa, eu sei, mas ainda assim), mas isso aconteceu:
private CentralDC _dc;
public bool UpdateDivision(ref DivisionWrapper division)
{
DivisionWrapper tempWrapper = division;
if (division.Entity == null)
{
return false;
}
try
{
Table<Division> table = _dc.Divisions;
var q = table.Where(o => o.ID == tempWrapper.Entity.ID);
if (q.Count() == 0)
{
division.Entity._errorMessage = "Unable to locate entity with id " + division.Entity.ID.ToString();
return false;
}
var realEntity = q.First();
realEntity = division.Entity;
_dc.SubmitChanges();
return true;
}
catch (Exception ex)
{
division.Entity._errorMessage = ex.Message;
return false;
}
}
Ao tentar enumerar sobre a consulta na memória, ocorreu a seguinte exceção: o membro da classe BaseObject.id é não mapeado. Embora eu esteja declarando o tipo e substituindo a propriedade ID L2S falha em funcionar. Alguma sugestão?
Solução
Suponha que eu encontrei o problema. Ao escrever
var q = table.Where(o => o.ID == tempWrapper.Entity.ID);
O compilador implica que o objeto é do tipo BaseObject e, portanto, tenta obter seu valor de identificação do mapeamento do BaseObject e não é mapeado. O problema parece ser resolvido declarando explicitamente o tipo:
var q = from Division div in _dc.GetTable<Division>()
where div.ID == tempWrapper.Entity.ID
select div;