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();

asynchronous option to be false

the asynchronous choice to be false to induce a synchronous Ajax request. Then your asking will set some information before your Main perform return.
Here's what your code would seem like if modified as suggested:

beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
            url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
            success: function (result) {
            if (result.isOk == false
                 alert(result.message);
            },
            async: false
         });
}
<script>
    // ...
    $.ajax(... async: false ...); // Hey browser! first complete this request,
                                  // then go for other codes

    $.ajax(...); // Executed after the completion of the previous async:false request.

</script>

Difference between Managed and unmanaged code


Managed code - Executed by the CLR instead of being executed by the operating system.

Unmanaged code - Executed directly by the operating system(OS) and not by the CLR

Adding an existing project to GitHub using the command line

How to Add project to git hub
1) Create new repository Copy Repository Url

2) Open ur project in Visual Studio
3) type: git init
git add *
ls

And Execte git hub generated commands

Build Connection String Dynamically

Entities _context = (Entities)HttpContext.Current.Session[SessionNames.xContext];
using WebSession = System.Web.HttpContext;

#region Build Connection String Dynamically
        public string BuildConnectionString(string dataSource, string database, string userId, string password)
        {
           //  string connect = BuildConnectionString(dataSource, custDbName, dbUserId, dbUserPassword);
            EntityConnectionStringBuilder retval = new EntityConnectionStringBuilder();
            //// Build the connection string from the provided datasource and database
            try
            {

                SqlConnectionStringBuilder sqlBuilder =
                    new SqlConnectionStringBuilder
                    {
                        DataSource = "x.x.x.x",
                        InitialCatalog = "xTemplate",
                        UserID = "x",
                        Password = "x",
                        IntegratedSecurity = false,
                        MultipleActiveResultSets = true
                    };


                retval = new EntityConnectionStringBuilder
                {
                    Metadata = "res://*/x.Client.csdl|res://*/x.Client.ssdl|res://*/x.Client.msl",
                    Provider = "System.Data.SqlClient",
                    ProviderConnectionString = sqlBuilder.ToString()
                };
                BuildDatabaseContext(retval.ToString());

            }
            catch (Exception e)
            {
               
                    throw;
            }
            return retval.ToString();
        }
        public void BuildDatabaseContext(string connectionString)
        {
            try
            {
                StoreContext(connectionString);
            }
            catch (Exception e)
            {
                    throw;
            }
        }
        public void StoreContext(string connect)
        {
            try
            {
                Entities context = new Entities(connect);
                WebSession.Current.Session[SessionNames.xContext] = context;
            }
            catch (Exception e)
            {
               
                    throw;
             }
        }

        #endregion