Hi,
I need your help again. I have a project in ASP.NET that I have to read data and put this data in a database.
This is done. The problem now is to relate these two tables.
I already made the relations in SQL Management Studio, but here in the project they don't work.
Explanation of the project:
One product can have more than one description.
So the descriptions must be in a different table
Now I will put the examples:
XML:
<products><product><id>100</id><name>Ball</name><price>15</price><quantity>2</quantity><description><comment>aaa</comment></description><description><comment>bbb</comment></description></product></products>
MODEL:
[Table("Table")] public class Product { public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int Quantity { get; set; } } [Table("Comentario")] public class Comment { [Key] public int Id {get;set;} public string DescriptionComment { get; set; } }
CONTROLLER:
private List<Product> ProcessImport(string path) { XDocument xDocument = XDocument.Load(path); List<Product> products = xDocument.Descendants("product").Select (p => new Product() { Id = Convert.ToInt32(p.Element("id").Value), Name=p.Element("name").Value, Quantity = Convert.ToInt32(p.Element("quantity").Value), Price = Convert.ToInt32(p.Element("price").Value), }).ToList(); List<Comment> comments = xDocument.Descendants("description").Select (t => new Comment() { DescriptionComment= t.Element("description").Value }).ToList(); foreach(var product in products) { var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id)); if (productInfo != null) { productInfo.Id = product.Id; productInfo.Name = product.Name; productInfo.Quantity = product.Quantity; productInfo.Price = product.Price; } else {
db.Products.Add(product); } db.SaveChanges(); } foreach (var comment in comments)
{
var commentInfo = db.Comments.SingleOrDefault(t => t.Id.Equals(comment.Id));
if(commentInfo != null)
{
commentInfo.Id = comment.Id;
commentInfo.DescriptionComment = comment.DescriptionComment;
}
else
{
db.Comments.Add(comment);
}
} return products; }
Does anyone have any idea how this is done?
Thanks for help me!