Пример #1
0
        public static string ImportBulkDataFromXml <T>(CarDealerContext context,
                                                       string inputXml,
                                                       Predicate <T> predicate,
                                                       string rootElement = null) where T : class, new()
        {
            var tableName = context
                            .GetType()
                            .GetProperties()
                            .FirstOrDefault(x
                                            => x
                                            .PropertyType
                                            .GenericTypeArguments
                                            .FirstOrDefault(gta => gta.Name == typeof(T).Name) != null)
                            ?.Name;
            var serializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(rootElement ?? tableName));
            var entities   = (serializer.Deserialize(new StringReader(inputXml)) as T[])
                             .Where(x => predicate(x))
                             .ToArray();
            var table = context.GetType().GetProperty(tableName).GetValue(context) as DbSet <T>;

            table.AddRange(entities);
            context.SaveChanges();
            return($"Successfully imported {entities.Length}");
        }