我尝试以这种方式序列化LINQ结果:
Private Sub btnXML_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnXML.Click
Try
Dim sourceForXML = From detail In PayrollRegisterModel.CompanyDetails
Join shifts In PayrollRegisterModel.Shifts On detail.Id_companydetail Equals shifts.Id_companydetail
Dim xmlFile As New Xml.Serialization.XmlSerializer(sourceForXML.GetType)
Dim xw As System.Xml.XmlWriter = Xml.XmlWriter.Create("C:/Abcom/XMLRegister.xml")
xmlFile.Serialize(xw, sourceForXML)
Catch ex As Exception
MsgBox(e.ToString)
End Try
End Sub 但在这条线上:
Dim xmlFile As New Xml.Serialization.XmlSerializer(sourceForXML.GetType) 我得到了这个错误:
**System.InvalidOperationException was caught
Message=To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. System.Data.Objects.ObjectQuery`1[[VB$AnonymousType_0`2[[Abcom.Payroll.Register.CompanyDetail, Abcom.Payroll.Register, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Abcom.Payroll.Register.Shift, Abcom.Payroll.Register, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Abcom.Payroll.Register, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] does not implement Add(System.Object).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.TypeScope.GetEnumeratorElementType(Type type, TypeFlags& flags)
at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at Abcom.Payroll.Register.MainWindow.btnXML_Click(Object sender, RoutedEventArgs e) in C:\Abcom\Inhouse Development Tools\Abcom.Payroll.Register\Abcom.Payroll.Register\MainWindow.xaml.vb:line 415**有人知道这是怎么回事吗?我该如何解决这个问题?
致以敬意,
克劳迪奥
发布于 2010-12-03 07:53:11
奇怪的是,您想序列化的。但是如果你愿意:只需将.ToList()添加到你的sourceForXML中,它就会被序列化。但结果会很奇怪。(不知道方法扩展在VB中是否可用,如果没有,则使用Enumerable.ToList( /* From .... Join ... here */))
Imho,一个好的解决方案是不使用匿名类型进行序列化。使用需要保存的属性创建类,然后使用linq创建该项目的列表,并在序列化该集合之后。在C#中,它类似于:
class DataForXml
{
public string Field1 {get; set;}
public string Filed2 {get; set;}
// other needed fields here
}您的方法应该将所需的信息提取到该类的实例中:
var xmlData = PayrollRegisterModel.CompanyDetails
.Join(/* other table */)
.Select(x => new DataForXml { Field1 = x.Field1, Field2 = x.Field2 /* init other props here*/})
.ToList();https://stackoverflow.com/questions/4341193
复制相似问题