PDA

View Full Version : ایجاد رابطه یک به یک و بروز خطا ! asp.net core - ef core 2.2



night-wolf
چهارشنبه 12 تیر 1398, 20:15 عصر
باسلام ، وقت بخیر.
من دو جدول به نام های User و Customer دارم که بصورت زیر پیاده شده و هردوی اینها از جدولی به نام BaseEntity ارث بری میکنن.


public abstract class BaseEntity
{
public BaseEntity()
{
Id = Guid.NewGuid();
}
[Key]
public Guid Id { get; set; }

[Display(Name = "تاریخ و زمان ثبت")]
public string InsertDateTime { get; set; }

[Display(Name = "تاریخ و زمان ویرایش")]
public string EditDateTime { get; set; }

[Display(Name = "وضعیت")]
public bool IsDeleted { get; set; }
}



public class User : BaseEntity
{
[Column(TypeName ="nvarchar(50)")]
public string UserName { get; set; }

[Column(TypeName = "nvarchar(80)")]
public string FullName { get; set; }

[Column(TypeName = "nvarchar(100)")]
public string Password { get; set; }
public bool IsActive { get; set; }


[Column(TypeName = "nvarchar(200)")]
public string Description { get; set; }

[ForeignKey("Role")]
public Guid RoleId { get; set; }
public virtual Role Role { get; set; }

public virtual Customer Customer { get; set; }
}



public class Customer : BaseEntity
{

[Column(TypeName = "nvarchar(80)")]
public string FullName { get; set; }

[Column(TypeName = "nchar(11)")]
public string Tell { get; set; }

[Column(TypeName = "nchar(11)")]
public string Mobile { get; set; }

[DatabaseGenerated(DatabaseGeneratedOption.Identity )]
public int Parvandeh { get; set; }

[Column(TypeName = "nvarchar(200)")]
public string Address { get; set; }

[Column(TypeName = "nvarchar(200)")]
public string Description { get; set; }

[Key, ForeignKey("User")]
public Guid UserId { get; set; }
public virtual User User { get; set; }
}


اینم کد OnmodelCreating


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne<Customer>(a => a.Customer)
.WithOne(b => b.User)
.HasForeignKey<Customer>(b => b.UserId);

modelBuilder.Entity<Customer>()
.HasKey(d => d.Id);
}

وقتی میخوام اطلاعات رو ثبت کنم در بخش DbContext.SaveChanges(); خطای زیر رو میده !



SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Customers_Users_UserId". The conflict occurred in database "Dentist", table "dbo.Users", column 'Id'.
The statement has been terminated


ممنون میشم راهنمایی کنید.:قلب:

EnKamran
چهارشنبه 12 تیر 1398, 20:31 عصر
https://www.entityframeworktutorial.net/efcore/one-to-one-conventions-entity-framework-core.aspx

night-wolf
چهارشنبه 12 تیر 1398, 20:56 عصر
اگر به کدهای من دقت میکردید منم اونجوری پیاده کردم و این منبع رو هم اتفاقا قبل پست گذاشتن دیده بودم بازم ممنون اما مشکلم حل نشد:افسرده:

mr.sirwan
چهارشنبه 12 تیر 1398, 23:35 عصر
کد نحوه مقدارهیتون رو هم بذارین