شروع به کار با EF Core 1.0 - قسمت 9 - بررسی رابطهی One-to-One
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۶/۰۵ ۱۶:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class UserProfile
{
public int UserProfileId { get; set; }
public string UserName { get; set; }
public virtual Cartable Cartable { get; set; }
} public class Cartable
{
public int CartableId { get; set; }
public virtual UserProfile UserProfile { get; set; }
} public class MyDBDataContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=testdb2;Integrated Security = true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Cartable>(entity =>
{
entity.Property(e => e.CartableId).ValueGeneratedNever();
entity.HasOne(d => d.UserProfile)
.WithOne(p => p.Cartable)
.HasForeignKey<Cartable>(d => d.CartableId);
});
}
public virtual DbSet<Cartable> Cartables { get; set; }
public virtual DbSet<UserProfile> UserProfiles { get; set; }
} public class Cartable
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CartableId { get; set; }
[ForeignKey("CartableId")]
[InverseProperty("Cartable")]
public virtual UserProfile UserProfile { get; set; }
} public class UserProfile
{
public int UserProfileId { get; set; }
public string UserName { get; set; }
[InverseProperty("UserProfile")]
public virtual Cartable Cartable { get; set; }
}
public class MyBlog
{
public int MyBlogId { get; set; }
public string Url { get; set; }
public MyBlogImage MyBlogImage { get; set; }
}
public class MyBlogImage
{
public int MyBlogImageId { get; set; }
public byte[] Image { get; set; }
public string Caption { get; set; }
public int MyBlogForeignKey { get; set; }
public MyBlog MyBlog { get; set; }
} modelBuilder.Entity<MyBlog>() .HasOne(p => p.MyBlogImage) .WithOne(i => i.MyBlog) .HasForeignKey<MyBlogImage>(b => b.MyBlogForeignKey);
یعنی یک کاربر یک پروفایل داردیعنی یک کاربر صفر یا یک پروفایل دارد (حداکثر یک پروفایل).
HasKey(row => row.Id);
HasRequired(row => row.User).WithRequiredDependent(row => row.UserProfile);
Property(row => row.Id).HasColumnName("UserId");