Tuesday, December 19, 2017

Generate class from database table -- Sql to C# properties generate

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Friday, December 8, 2017

Potential runtime violation of table MigrationHistory's keys (MigrationHistory.MigrationId): Columns (MigrationHistory.MigrationId) are mapped to EntitySet MigrationHistories's properties (MigrationHistories.MigrationId) on the conceptual side but they do not form the EntitySet's key properties (MigrationHistories.ContextKey, MigrationHistories.MigrationId).

Error a pair of Error 3002: drawback in mapping fragments beginning at line 2532:Potential runtime violation of table MigrationHistory's keys (MigrationHistory.MigrationId): Columns (MigrationHistory.MigrationId) ar mapped to EntitySet MigrationHistories's properties (MigrationHistories.MigrationId) on the abstract aspect however they are doing not type the EntitySet's key properties (MigrationHistories.ContextKey, MigrationHistories.MigrationId).


The reason was in strange update results of EF model update operation. table seeable (database) continues to be a key, however in model read it had been deleted(automatically) from set of keys. however not everyplace or one thingelse... therefore the resolution - Set Entity Key to False and Nullable to True not for brand new fields, except for table

<EntityType Name="MigrationHistory">
          <Key>
            <PropertyRef Name="MigrationId" /> Find MigrationHistory
     <PropertyRef Name="ContextKey" /> Add this keys
    </Key>
          <Property Name="MigrationId" Type="nvarchar" MaxLength="150" Nullable="false" />
          <Property Name="ContextKey" Type="nvarchar" MaxLength="300" Nullable="false" />
          <Property Name="Model" Type="varbinary(max)" Nullable="false" />
          <Property Name="ProductVersion" Type="nvarchar" MaxLength="32" Nullable="false" />
        </EntityType>

Tuesday, November 21, 2017

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

Tuesday, October 31, 2017

Join Query Multiple Tables Order by descending Order

var year = (from ep in _adminContext.table1
                    join e in _adminContext.table2 on ep.idequals e.id
                    join t in _adminContext.table3 on e.idequals t.id
                    orderby t.Date descending
                    where t.status == "A"
                    select new
                    {
                        id= ep.id

                    }).FirstOrDefault();