25 Aralık 2015 Cuma

Nesne büyüklüğü öğrenme

    /// <summary>
    /// Calculates the lenght in bytes of an object 
    /// and returns the size 
    /// </summary>
    /// <param name="TestObject"></param>
    /// <returns></returns>
    private int GetObjectSize(object TestObject)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        byte[] Array;
        bf.Serialize(ms, TestObject);
        Array = ms.ToArray();
        return Array.Length;
    }

18 Aralık 2015 Cuma

Entity Framework one-to-zero or one relationship

Configure One-to-One Relationship:

We are going to configure a One-to-One relationship between Student and StudentAddress. As you may know, a one-to-one relationship happens when the primary key of one table becomes PK & FK in another table. Here, StudentId is a Primary key of Student table so StudentId should be PK and FK in StudentAddress table in order to have one-to-one (actually one-to-zero or one) relationship between them.
Note that a one-to-one relationship is technically not possible in MS SQL Server. It will always be one-to-zero or one.
Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many, and many-to-many relationships.

Configure one-to-zero or one relationship using DataAnnotations:

The following example shows one-to-one relationship is configured using DataAnnotations attributes.
public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress StudentAddress { get; set; }

}
     
public class StudentAddress 
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}
        
As you can see in the above Student and StudentAddress class, we haven't done anything special in Student class because it follows the code first conventions, so StudentId will become PK. Now, we have used the Key and ForeignKey attributes for StudentId property in StudentAddress class, in order to mark it as PK as well as FK. Notice that we have specified Student entity in the ForeignKey attribute. Thus, Code-First will create a one-to-one relationship between Student and StudentAddress using DataAnnotations attributes.

Configure One-to-Zero-or-One relationship using Fluent API:

The following example sets one-to-zero or one relationship between Student and StudentAddress using Fluent API.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);
        
    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasOptional(s => s.StudentAddress) // Mark StudentAddress is optional for Student
                .WithRequired(ad => ad.Student); // Create inverse relationship

}
        
As you can see in the above example, we set primary key to StudentId for StudentAddress because it doesn't follow the Code-First conventions for PK. In the second line, HasOptional method makes StudentAddress property nullable and then WithRequired method creates inverse relationship by making StudentId column as FK in StudentAddress table. Thus, StudentId will be PK and FK in StudentAddress which makes one-to-zero or one relationship.
Alternatively, you can also configure StudentAddress entity, as shown below.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);
        
    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
                .HasRequired(ad => ad.Student) 
                .WithOptional(s => s.StudentAddress); 

}
        
So, DataAnnotations and Fluent API example for one-to-zero or one relationship will create the following database:
one-to-one relationship in code first
You can check the relationship between Student and StudentAddress in the database, as shown below:
one-to-one relationship in code first
If you create an entity data model of a created database then it will appear like the diagram shown below:
one-to-one relationship in code first
Learn how to create a one-to-many relationship in the next section.

15 Aralık 2015 Salı

string tarihi DateTime a çevirme

 string dateText = "21/12/2015";
var date = DateTime.ParseExact(dateText , "dd/MM/yyyy", null);

14 Aralık 2015 Pazartesi

Tüm paketleri güncelleme

Updating All Packages

Issue: 431
There is currently no easy way to update all packages within a solution. In this iteration, we’ll update the Update-Package command to support updating all packages at the solution level and project level. We will not be adding support for this to the Add Package Dialog in this iteration, but will consider it for a future iteration. We just need to think through the UI for that.
Command Description
Update-Package Updates all packages in all projects.
Update-Package –Project ProjectName Updates all packages in the specified project
Update-Package PackageId Breaking Change: Updates the specified package in all projects rather than just the current project
Update-Package PackageKid –Project ProjectName No change: Updates the specified package in the specfied project only as before.
Update-Package –Safe  New –Safe flag only updates packages to the next “safe” version, which is the latest version with the same major and minor version number as the current package.

13 Aralık 2015 Pazar

DB’deki tüm tablolardaki kayıt sayısı ve index boyutunu hesaplamak

Database deki tüm kayıtları tablo bazında ve diskte ne kadar yer kapladığınız sorgulamak için kullanılacak bir script.

SET nocount ON
CREATE TABLE #spaceused
 (name NVARCHAR(120) ,
 rows CHAR(11) ,
 reserved VARCHAR(18) ,
 data VARCHAR(18) ,
 index_size VARCHAR(18) ,
 unused VARCHAR(18))
DECLARE Tables CURSOR
FOR
SELECT sys.schemas.name + '.' + sys.objects.name
      FROM sys.objects
      INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
      WHERE sys.objects.type = 'U'
OPEN Tables
DECLARE @table VARCHAR(128)
FETCH NEXT FROM Tables INTO @table
WHILE @@FETCH_STATUS = 0
      BEGIN
           INSERT INTO #spaceused
           EXEC sp_spaceused @table
           FETCH NEXT FROM Tables INTO @table
      END
CLOSE Tables
DEALLOCATE Tables
SELECT *
FROM #spaceused
ORDER BY CAST([rows] AS BIGINT) DESC
DROP TABLE #spaceused
EXEC sp_spaceused
Script çalıştırıldığında aşağıda görüldüğü üzere tablo bazında satır sayısı ve diskte ne kadar yer kapladığı görüntülenebilmektedir.

4 Aralık 2015 Cuma

EntityFramework savechanges olmadan önce bir önceki değeri alma

db.Users.Attach(user);
var current = db.Entry(user).CurrentValues.Clone();
db.Entry(user).Reload();
//Do you user(from db) stuff
db.Entry(user).CurrentValues.SetValues(current);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();

.net 6 mapget kullanımı

 app.UseEndpoints(endpoints => {     endpoints.MapGet("/", async context =>     {         var response = JsonConvert.Seriali...