Skip to content

Commit

Permalink
Merge b9c3062 into f766827
Browse files Browse the repository at this point in the history
  • Loading branch information
atifaziz authored Jun 25, 2023
2 parents f766827 + b9c3062 commit 0f599d6
Showing 1 changed file with 22 additions and 27 deletions.
49 changes: 22 additions & 27 deletions MoreLinq/ToDataTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,20 +189,6 @@ static MemberInfo[] BuildOrBindSchema(DataTable table, MemberInfo[] members)

var columns = table.Columns;

var schemas = from m in members
select new
{
Member = m,
Type = (m.MemberType == MemberTypes.Property
? ((PropertyInfo)m).PropertyType
: ((FieldInfo)m).FieldType) switch
{
var type when Nullable.GetUnderlyingType(type) is { } t => t,
var type => type,
},
Column = columns[m.Name],
};

//
// If the table has no columns then build the schema.
// If it has columns then validate members against the columns
Expand All @@ -211,25 +197,34 @@ var type when Nullable.GetUnderlyingType(type) is { } t => t,

if (columns.Count == 0)
{
columns.AddRange(schemas.Select(m => new DataColumn(m.Member.Name, m.Type)).ToArray());
foreach (var member in members)
_ = columns.Add(member.Name, GetElementaryTypeOfPropertyOrField(member));

return members;
}
else
{
members = new MemberInfo[columns.Count];

foreach (var info in schemas)
{
var member = info.Member;
var column = info.Column ?? throw new ArgumentException($"Column named '{member.Name}' is missing.", nameof(table));
var columnMembers = new MemberInfo[columns.Count];

if (info.Type != column.DataType)
throw new ArgumentException($"Column named '{member.Name}' has wrong data type. It should be {info.Type} when it is {column.DataType}.", nameof(table));
foreach (var member in members)
{
var column = columns[member.Name] ?? throw new ArgumentException($"Column named '{member.Name}' is missing.", nameof(table));

members[column.Ordinal] = member;
}
if (GetElementaryTypeOfPropertyOrField(member) is var type && type != column.DataType)
throw new ArgumentException($"Column named '{member.Name}' has wrong data type. It should be {type} when it is {column.DataType}.", nameof(table));

columnMembers[column.Ordinal] = member;
}

return members;
return columnMembers;

static Type GetElementaryTypeOfPropertyOrField(MemberInfo member) =>
(member.MemberType == MemberTypes.Property ? ((PropertyInfo)member).PropertyType
: ((FieldInfo)member).FieldType)
switch
{
var type when Nullable.GetUnderlyingType(type) is { } ut => ut,
var type => type,
};
}

static Func<T, object[]> CreateShredder<T>(IEnumerable<MemberInfo> members)
Expand Down

0 comments on commit 0f599d6

Please sign in to comment.