我正在研究EPG申请。目标很简单:1)从url读取XMLTV,2)将xml反序列化为对象并保存到db,3)从db读取对象并再次序列化。
要做到这一点,我使用Entity Framework,代码优先方法,因为我认为这是最快的方式 - 我需要复制整个xml文档,然后粘贴特殊的“粘贴XML作为类”,然后我得到几乎完整的类模型。 出于演示目的,我将仅使用XMLTV中的两个类 - 根元素'tv'的类和一个名为'channel'的根元素的子类(whole XMLTV包含44个元素)。
到目前为止,我上课了:
[Serializable]
[XmlRoot("tv")]
public class Tvs
{
public Tvs()
{
}
[Key]
[XmlIgnore]
public int TvID { get; set; }
[XmlElement("channel")]
public Channels[] channels { get; set; }
[XmlAttribute]
public string date { get; set; }
[XmlAttribute("source-info-url")]
public string sourceinfourl { get; set; }
[XmlAttribute("source-info-name")]
public string sourceinfoname { get; set; }
[XmlAttribute("source-data-url")]
public string sourcedataurl { get; set; }
[XmlAttribute("generator-info-name")]
public string generatorinfoname { get; set; }
[XmlAttribute("generator-info-url")]
public string generatorinfourl { get; set; }
}
[Serializable]
public class Channels
{
public Channels()
{
}
[Key]
[XmlIgnore]
public int ChannelID { get; set; }
[XmlElement]
public string[] url { get; set; }
[XmlAttribute]
public string id { get; set; }
[ForeignKey("TvID")]
[XmlIgnore]
public Tvs Tv { get; set; } // navigation property
[XmlIgnore]
public int TvID { get; set; }
}
...我也得到了背景:
class TvContext : DbContext
{
public TvContext() : base("EntityDataModel") // connection string in App.config
{
}
public DbSet<Tvs> tvs { get; set; }
public DbSet<Channels> channels { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
主程序:
static void Main(string[] args)
{
String url = "http://tvprofil.net/xmltv/data/htv1.hr/weekly_htv1.hr_tvprofil.net.xml";
String xml;
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
xml = client.DownloadString(url);
//Console.WriteLine(xml);
}
var serializer = new XmlSerializer(typeof(Tvs));
Tvs result;
using (TextReader reader = new StringReader(xml))
{
result = (Tvs)serializer.Deserialize(reader); // RESULT CONTAINS WHOLE DOCUMENT - TV AND CHANNELS ARE INITIALIZED
}
using (var db = new TvContext())
{
db.tvs.Add(result);
db.SaveChanges();
}
using (var db = new TvContext())
{
var query = from b in db.tvs // IN DB AND THIS QUERY VARIABLE ONLY TVS ARE INITIALIZED; B.CHANNELS ARE NULL
select b;
foreach (Tvs item in query)
{
Console.WriteLine(XmlManipulation.GetXMLFromObject(item));
}
}
Console.ReadKey();
}
问题:因此,正如您在主程序中看到的那样,我成功地从url获取XML文档并将其反序列化为Tvs对象(初始化相关通道)。如果我打开数据库来查看数据,有电视,但没有保存的频道。拜托,有谁能告诉我这里做错了什么。