我正在创建一个WCF Web服务。
我试图根据从数据库返回的信息创建一个Type,构建一个带有数据的Type列表,并将其发回。
但是,我得到了一个
键入'MyDynamicType‘,其数据契约名为'MyDynamicType:http://schemas.datacontract.org/2004/07/’,这是不需要的。考虑使用DataContractResolver或将任何类型静态地添加到已知类型列表中,例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。跟踪查看器中出现错误。
研究这个例外。它建议将该类型添加到[KnownTypes(Type)]中。我如何使用这样创建的Type来完成这个任务?
Type类代码来自How to dynamically create a class in C#?,只做了很小的修改。(即分离创建类型和实例创建。)
Web服务终结点
[OperationContract]
[WebInvoke(Method = "GET",
UriTemplate = "/DB/{Q}")]
List<object> DB(string Q);Web服务端点代码
public List<object> DB(string Q)
{
List<object> rows = DLL.DB.RunQuery(IQueries.LoadQuery(Q));
return rows;
}运行查询方法
public static List<object> RunQuery(string query)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = query;
connection.Open();
using (SqlDataAdapter da = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
da.Fill(dt);
Dictionary<string, Type> columns = new Dictionary<string, Type>();
foreach (DataColumn dc in dt.Columns)
{
columns.Add(dc.ColumnName, dc.DataType);
}
Type customType = MyTypeBuilder.CreateNewObject(columns);
List <object> rows = new List<object>();
foreach (DataRow dr in dt.Rows)
{
List<object> row = new List<object>();
foreach (DataColumn col in dt.Columns)
{
object customInstance = MyTypeBuilder.CreateObjectInstance(customType);
PropertyInfo pi = customType.GetProperty(col.ColumnName);
pi.SetValue(customInstance, dr[col]);
row.Add(customInstance);
}
rows.Add(row);
}
return rows;
}
}
}
}我的类型生成器
public class MyTypeBuilder
{
public static object CreateObjectInstance(Type myType)
{
var myObject = Activator.CreateInstance(myType);
return myObject;
}
public static Type CreateNewObject(Dictionary<string,Type> values)
{
var myType = CompileResultType(values);
return myType;
}
public static Type CompileResultType(Dictionary<string, Type> values)
{
TypeBuilder tb = GetTypeBuilder();
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
// NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
foreach (var field in values)
CreateProperty(tb, field.Key, field.Value);
Type objectType = tb.CreateType();
return objectType;
}
private static TypeBuilder GetTypeBuilder()
{
var typeSignature = "MyDynamicType";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout |
TypeAttributes.Serializable
, null);
return tb;
}
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
}提前谢谢。
发布于 2016-07-25 17:45:16
也许您可以拥有所有动态类型继承的基类。然后,您可以将基类作为knownTypes装饰器中的基类。
发布于 2016-07-26 13:51:21
这里有一些简单的代码让你开始,
[KnownType(typeof(YourSpecialObject))]
[DataContract]
public abstract class BusinessObjectInfo
{
[DataMember]
public int Id { get; set; }
[DataMember]
public Byte[] Version { get; set; }
}现在你的特殊对象
[DataContract]
public class YourSpecialObject: BusinessObjectInfo现在,您的WCF应该解析KnownTypes。作为一种学习方法,僵尸资源管理器将拥有关于.NET / WCF /PRISM的大量信息,这里链接到WCF的一个相当彻底的例子,http://www.codeproject.com/Articles/474212/Zombie-Explorer-An-n-tier-application-from-top-to
发布于 2016-07-29 08:13:55
我会用一种完全不同的更容易的方式来做。我的解决办法是基于以下理由:
MyDynamicType是基于数据表结构->创建的MyDynamicType的实例实际上是行。->MyDynamicType的实例实际上是键/值集合。->MyDynamicType。用一本简单的字典就足够了。本词典中的键将是列的名称,值将对应于单元格(列的值)。据我所知,WCF使用DataContractJsonSerializer将数据序列化为JSON格式,并且我非常肯定它正确地处理字典。也可以阅读this的文章。
您还可以使用另一个序列化程序,而不是默认的序列化程序,例如Newtonsoft Json.Net序列化程序。参见this或this问题。
最后,为什么实际上使用WCF来创建像API一样的REST呢?我认为WebApi更容易使用,除非您有一些具体的理由使用WCF。
https://stackoverflow.com/questions/38516046
复制相似问题