我正在尝试将其转换IEnumerable<IEnumerable<string>>
为ICollection<Character>
但努力找出正确的方法,因为一个对象的结构与另一个对象的结构不同。
转换的原因是进行 json 反序列化并通过 Entity Framework 将其插入数据库。json 数据未规范化,与数据库的确切结构不匹配。在数据库中,我有一个movie
和一个person
具有多对多关系的。他们之间的桥梁表是characters
。但是 json 中只有一个包含人物对象数组的电影对象,每个人都有他们扮演的角色数组(IEnumerable<IEnumerable<string>>
)。
基本上,我需要将每部电影的人物及其角色转换为每部电影的角色及其各自的人物。
var movie = dataContractMovies.Select(m => new Movie {
Title = m.Title,
// not sure how to convert each Person and their characters
Characters = // Need to take each Person and their Characters in m.Cast and cast to a new Character and a new Person for which the Character belongs to
});
转换自
public class MovieDataContract {
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "abridged_cast")]
public virtual IEnumerable<Person> Cast { get; set; }
}
[DataContract]
public class Person {
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "characters")]
public IEnumerable<string> Characters { get; set; }
}
转换成
public partial class Movie {
public string Title { get; set; }
public virtual ICollection<Character> Characters { get; set; }
public Movie() {
this.Characters = new HashSet<Character>();
}
}
public partial class Character {
public string Name { get; set; }
public virtual Movie Movie { get; set; }
public virtual Person Person { get; set; }
}
public partial class Person {
public string Name { get; set; }
public virtual ICollection<Character> Characters { get; set; }
public Person() {
this.Characters = new HashSet<Character>();
}
}
更新和进一步的问题
如果我只是public IEnumerable<Character> Characters
在MovieDataContract
? 然后我可以做这样的事情(理论上,没有测试过)......
Characters = m.Characters;
所以我的新MovieDataContract
产品看起来像这样......
[DataContract]
public class MovieDataContract {
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "abridged_cast")]
private IEnumerable<Person> _cast { get; set; }
public IEnumerable<Character> Characters {
get{
foreach(var person in _cast) {
foreach(string name in person.characters) {
yield return new Character { Name = name, Person = new Person { Name = person.name }}
}
}
}
}
}