Entity Framework etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Entity Framework etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

30 Temmuz 2018 Pazartesi

Tüm TimeZone'ları çekip veritabanına ekleme

            var tzCollection = TimeZoneInfo.GetSystemTimeZones();
            var timeZoneTypes = new List<TimeZoneType>();
            foreach (var timeZoneInfo in tzCollection)
            {
                var timeZoneType = new TimeZoneType
                {
                    TimeZoneInfoId = timeZoneInfo.Id,
                    DaylightName = timeZoneInfo.DaylightName,
                    DisplayName = timeZoneInfo.DisplayName,
                    StandardName = timeZoneInfo.StandardName,
                    SupportsDaylightSavingTime = timeZoneInfo.SupportsDaylightSavingTime,
                    Ticks = timeZoneInfo.BaseUtcOffset.Ticks
                };
                timeZoneTypes.Add(timeZoneType);
            }
            foreach (var timeZoneType in timeZoneTypes)
            {
                db.TimeZoneTypes.Add(timeZoneType);

                db.Commit();
            }


11 Nisan 2016 Pazartesi

mysql migration sorunları

guid alanı long'a çevirdim mysql ilk migration'da guid alan için trigger oluşturmuş bu trigger silmek gerekiyordu
 DROP TRIGGER IF EXISTS Trigger_Adı komutu ile trigger sildim
daha sonra ayno tabloya atılan bir kaç kayıt vardı, id'si guid olan onları da sildim düzeldi.
 

9 Şubat 2016 Salı

Entity framework tablo var mı

            bool exists = context.Database
                      .SqlQuery<int?>(@"
                         SELECT 1 FROM sys.tables AS T
                         INNER JOIN sys.schemas AS S ON T.schema_id = S.schema_id
                         WHERE S.Name = 'SchemaName' AND T.Name = 'Table_Name' ")
                      .SingleOrDefault() != null;

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.

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

30 Eylül 2015 Çarşamba

entity framework code first - birden fazla foreign key aynı tabloda ise

public class Team
{
    public int TeamId { get; set;} 
    public string Name { get; set; }

    public virtual ICollection<Match> HomeMatches { get; set; }
    public virtual ICollection<Match> AwayMatches { get; set; }
}

public class Match
{
    public int MatchId { get; set; }

    public int HomeTeamId { get; set; }
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}


public class Context : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HomeTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HomeTeamId)
                    .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
    }
}

9 Mayıs 2015 Cumartesi

Entity Framework Migrate Database to Latest Version

  public class DatabaseContext : DbContext
    {
        public DatabaseContext()
            : base("name=DatabaseContext")
        {
            //Eğer modelde bir değişiklik olduysa veritabanını günceller
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
        }
}

5 Mayıs 2015 Salı

Entity framework Hashset

    public class Post
    {
        [SuppressMessage("ReSharper", "DoNotCallOverridableMethodsInConstructor")]
        public Post()
        {
            Likes = new HashSet<Like>();
            Post1 = new HashSet<Post>();
        }
....
diyelim mesala burda her like'dan bir tane olacağı anlamına geliyor. Likes listesindeki bütün veriler farklı oluyor. Tekrar eden sütun olmuyor ki olmaması da lazım veri tutarlılığı için

.net 6 mapget kullanımı

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