当我在ASP.NET Core中的数据库中创建关系时,可以创建新数据

发布于 2025-02-10 22:04:12 字数 1056 浏览 2 评论 0原文

我在我的ASP.NET核心项目中创建了两个模型类(Company位置),并使用实体框架创建了使用视图的控制器。然后,我添加了迁移并更新了数据库。一切都很好(CRUD),直到我尝试建立关系(使用外键)。

当我在location模型中添加此代码行时:

public virtual ICollection<Company> Companies { get; set; }

我再也无法创建新位置了。当我添加以下行时,公司也一样:

public int LocationId { get; set; }
public virtual Location Location { get; set; }

我有0个错误,但是当我单击创建按钮时,什么也不会发生。

我的模型看起来像这样:

public class Company
{
    public int CompanyId { get; set; }
    public string CompanyName { get; set; }
    public string? Phone { get; set; }

    public int LocationId { get; set; }
    public virtual Location Location { get; set; }

    public Company()
    {
    }
}

public class Location
{
    public int LocationId { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Company> Companies { get; set; }

    public Location()
    {
    }
}

I created two model classes (Company and Location) in my ASP.NET Core project and created controllers with views using Entity Framework. Then I added migration and updated database. Everything worked just fine (CRUD) until I've tried to create a relations (using foreign keys).

When I added this line of code in my Location model:

public virtual ICollection<Company> Companies { get; set; }

I couldn't create new locations anymore. Same for the companies when I added these lines:

public int LocationId { get; set; }
public virtual Location Location { get; set; }

I have 0 errors, but nothing happens when I click on Create button.

My models look like this:

public class Company
{
    public int CompanyId { get; set; }
    public string CompanyName { get; set; }
    public string? Phone { get; set; }

    public int LocationId { get; set; }
    public virtual Location Location { get; set; }

    public Company()
    {
    }
}

public class Location
{
    public int LocationId { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Company> Companies { get; set; }

    public Location()
    {
    }
}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文