将播种数据到DB表:如何在OnModeLcreating()中配置FK?

发布于 2025-02-03 06:49:29 字数 1392 浏览 4 评论 0原文

我正在通过EF迁移将数据播种到SQL表。使用on ModelCreating。 表I正在播种数据,在其他表中有FK。如何在OnModelCreating中配置它?

  modelBuilder.Entity<UserEntity>().HasData(
                new UserEntity
                {
                    Id = Guid.NewGuid(),
                    CreatedAt = DateTime.Now,
                    CreatedBy = Guid.Empty,
                    Email = "[email protected]",
                    FirstName = "Jake",
                    LastName = "Carter"
                    
                }
            );

这些属性不是FKS。 还有另一个属性 - fefereNdicatiCatorId是FK。 我如何将其放入跨模型中?

更新 : 我尝试创建preferendicnicator对象,并在hasdata()中设置PrefenrenceIndicator,但是在添加迁移后,up()和down()方法为空。

modelBuilder.Entity<UserEntity>().HasData(
                new UserEntity
                {
                    Id = Guid.NewGuid(),
                    CreatedAt = DateTime.Now,
                    CreatedBy = Guid.Empty,
                    Email = "[email protected]",
                    FirstName = "Jake",
                    LastName = "Carter",
                    PreferenceIndicator = preferenceIndicator
                }
            );

I'm seeding data to SQL table through EF migration. Using OnModelCreating.
Table I am seeding data in, has FK to other table. How do I configure that in OnModelCreating?

  modelBuilder.Entity<UserEntity>().HasData(
                new UserEntity
                {
                    Id = Guid.NewGuid(),
                    CreatedAt = DateTime.Now,
                    CreatedBy = Guid.Empty,
                    Email = "[email protected]",
                    FirstName = "Jake",
                    LastName = "Carter"
                    
                }
            );

These properties aren't FKs.
There is one more property - PreferenceIndicatorId which is FK.
How do I put that in OnModelCreating?

UPDATE :
I tried creating PreferenceIndicator object and set the PrefenrenceIndicator in HasData() but after adding migration, Up() and Down() methods were empty.

modelBuilder.Entity<UserEntity>().HasData(
                new UserEntity
                {
                    Id = Guid.NewGuid(),
                    CreatedAt = DateTime.Now,
                    CreatedBy = Guid.Empty,
                    Email = "[email protected]",
                    FirstName = "Jake",
                    LastName = "Carter",
                    PreferenceIndicator = preferenceIndicator
                }
            );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

氛圍 2025-02-10 06:49:29

您的喜好已经存在吗?

还是您正在创建一个新的?

一般来说。

如果您的preferendicnicator(相关对象)确实“预先存在”,则可以设置

userentity.preferenceIndicatorId to此已知值。

这里一个好的隐喻将是“添加员工”功能。

大多数时候,当您添加新员工时,您的员工。DepartmentKey将来自已经创建的行。

因此,您可以将员工实体的部门设置为确切的价值。

Employee emp = new Employee();

emp.DepartmentKey = 333; /* 333 already exists in the database/dept-table */

....

如果您的关系对象没有“预先存在”。

当然,这是更棘手的情况。

在这里,您不会在示例中或在我的示例中the Employee.departmentKey设置outer-key标量标量(userentity.preferenceIndicatiCatorId)。这是有道理的,您无法设置FK标量值,因为它尚不存在。

您需要对导航对象/属性进行编码,并允许EF为您完成工作。

但是,您还需要设置倒数值。

例如:

public class Department
{


    public Department()
    {
        this.Employees = new List<Employee>();
    }


    public long DepartmentKey { get; set; }

    public ICollection<Employee> Employees { get; set; }

public class Employee
{

    public long EmployeeKey { get; set; }

public long MyParentDepartmentKey { get; set; } /* the scalar FK value */


    public Department MyParentDepartment { get; set; } /* the full object */

..

注意,部门与员工有1:N的关系。 (无论是1:1,1:1:n还是m:n不是这里的主要关注点,而是您需要编写“倒数”方面。

同样,以下代码与该部门有关“

Department dept = new Department();


Employee emp1 = new Employee();
emp1.MyParentDepartment = dept;


// and now what is often overlooked, the RECIPROCAL relationship

dept.Employees.Add(emp1);

现在您可以做一些

myDbContext.Departments.Add(dept);
myDbConext.SaveAsync(CancellationToken.None); << you should NOT use 
.None here in your real code.

记住之类的事情,部门设置了为员工设置的导航属性……但是,您的员工在该部门的员工设有其MyParentDepartment。

请注意,设置了导航属性对象,而没有FK - 设置(因为它们尚不清楚)(在这里

呼叫.saveasync之后,MyParentDepartmentKey作为主要示例,您应该查看MyDbContext中的对象。一个FK,

简而言之,设置导航标量。
设置导航对象/属性(并在这些对象没有预先存在的情况下)。

请注意,我的部门和员工代码假设(并且除非)已设置属性ORM映射代码,否则将行不通。这不是“魔术仙女尘”。

See:

https://www.learnentityframeworkcore.com/configuration/one-待办事项关系 - 配置

个人提示:

如果您停止使用type/propertyname的模棱两可的名称,则可以更好地学习EF。

而不是

public Employee

   public Department Department {get; set;}

这就是为什么我使用

public Employee

   public Department MyParentDepartment {get; set;}

甚至

public Employee

   public Department TheDepartment {get; set;}

任何东西来消除歧义的原因。

......

您还可以在以下示例中看到此“水合物体,而不是标量”:

https://www.learnentityframeworkcore.com/dbcontext/adding-data

(页面末尾)的部分中

在标记

var context = new SampleContext();
var author = new Author { FirstName = "Stephen", LastName = "King" };
var books = new List<Book> {
    new Book { Title = "It", Author = author },
    new Book { Title = "Carrie", Author = author },
    new Book { Title = "Misery", Author = author }
};
context.AddRange(books);
context.SaveChanges();

为“添加多个记录” 正在设置值。但是这本书是由较低案例“作者”设置的作者导航属性。

在执行.savechanges之后。(当然也不例外)...如果您看对象...然后您会看到主要的键和外keyscalars是水合的

Does your PreferenceIndicator already exist?

Or are you creating a new one?

In general.

If your PreferenceIndicator (related object) does "pre-EXIST", then you can set the

UserEntity.PreferenceIndicatorId to this known value.

A good metaphor here would be an "Add Employee" functionality.

Most times, when you add a new Employee, your Employee.DepartmentKey will come from already created rows.

Thus you can set the Employee entity's DepartmentKey to an exact value.

Employee emp = new Employee();

emp.DepartmentKey = 333; /* 333 already exists in the database/dept-table */

....

If your relationship object does NOT "pre-exist".

This of course is the trickier situation.

Here you will NOT set the foreign-key SCALAR (UserEntity.PreferenceIndicatorId in your example or in my example the Employee.DepartmentKey). And this makes sense, you cannot set the FK SCALAR value because it does not exist yet.

You need to code the the NAVIGATION OBJECTS/PROPERTIES and allow EF to do the work for you.

BUT, you also need to setup the reciprocal values.

For example:

public class Department
{


    public Department()
    {
        this.Employees = new List<Employee>();
    }


    public long DepartmentKey { get; set; }

    public ICollection<Employee> Employees { get; set; }

and

public class Employee
{

    public long EmployeeKey { get; set; }

public long MyParentDepartmentKey { get; set; } /* the scalar FK value */


    public Department MyParentDepartment { get; set; } /* the full object */

..

Note, the Department has a 1:N relationship with Employees. (Whether it is 1:1, 1:N or M:N is not the primary concern here, but you need to code up the "reciprocal" side of things.

Again the below code is about the Department does not "pre-exist"

Department dept = new Department();


Employee emp1 = new Employee();
emp1.MyParentDepartment = dept;


// and now what is often overlooked, the RECIPROCAL relationship

dept.Employees.Add(emp1);

and now you can do something like

myDbContext.Departments.Add(dept);
myDbConext.SaveAsync(CancellationToken.None); << you should NOT use 
.None here in your real code.

Remember, dept has a navigation property set for employee(S)...but also, your employee in that department has its MyParentDepartment set.

Note, navigation property OBJECTS were set, and none of the FK-SCALARS were set (because they are not known yet) (MyParentDepartmentKey as the main example here).

AFTER you call .SaveAsync, you should look at the objects in the myDbContext....and you should see hydrated Primary-Keys and the one FK.

In short, set navigation SCALARS when they pre-exist.
set navigation object/properties (and RECIPROCATE these objects) when they do not pre-exist.

Note, my Department and Employee code ASSUMES that (and will not work unless) you have setup the property ORM mapping code already. it is not "magic fairy dust".

See:

https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration

Personal tip:

You will learn EF better if you stop using ambiguous names for Type/PropertyName.

Instead of

public Employee

   public Department Department {get; set;}

This is why I use

public Employee

   public Department MyParentDepartment {get; set;}

or even

public Employee

   public Department TheDepartment {get; set;}

or anything to disambiguate.

......

You can also see this "hydrate OBJECTS, not SCALARS" in the example at:

https://www.learnentityframeworkcore.com/dbcontext/adding-data

In the section labeled "Adding Multiple Records" (towards the end of the page)

The code:

var context = new SampleContext();
var author = new Author { FirstName = "Stephen", LastName = "King" };
var books = new List<Book> {
    new Book { Title = "It", Author = author },
    new Book { Title = "Carrie", Author = author },
    new Book { Title = "Misery", Author = author }
};
context.AddRange(books);
context.SaveChanges();

No "primary key" or "foreign key" values are being set. BUT the Book.Author navigation property is being set by the lower case "author".

After .SaveChanges is executed..(and no exceptions of course)... if you look at the objects... you'll then see the PrimaryKey and ForeignKeySCALARS as being hydrated

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文