【问题标题】:Difficulty using "public virtual" variables in database creation难以在数据库创建中使用“公共虚拟”变量
【发布时间】:2012-02-14 07:03:37
【问题描述】:

我正在使用以下代码在 Visual Web Developer 2010 Express 中创建两个表:

http://imgur.com/a/Mi2Bv(不好意思,论坛不让我了,因为是新账号,直接发图)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BarApp.Models
{
    public class Drinks
    {
        public int DrinksId { get; set; }
        public int EstablishmentsID { get; set; }
        public string name { get; set; }
        public decimal price { get; set; }
        public string description { get; set; }
        public string image { get; set; }

        public virtual Establishments establishment { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BarApp.Models
{
    public class Promotions
    {
        public int PromotionsId { get; set; }
        public string name { get; set; }
        public float discount { get; set; }
        public int EstablishmentId { get; set; }
        public int DrinkId { get; set; }
        public string description { get; set; }

        public virtual Establishments establishment { get; set; }
        public virtual Drinks drink { get; set; }
    }
}

但是当我查看创建的表时,Promotions 表包含公共虚拟代码的实际行,而 Drinks 表没有。

我可以让 Drinks 表按照我在项目其他地方想要的方式运行,但我无法让 Promotions 以相同的方式运行,因为“公共虚拟”似乎在每个表中给出了不同的结果。

我不明白为什么我的 Promotions 表实际上是为公共虚拟变量创建行。有人可以帮我理解吗?

【问题讨论】:

  • 经过进一步阅读,我了解到“虚拟”与以下内容有关:“您正在延迟加载艺术家和流派,这涉及再次返回 SQL Server,所以您是实际上在这里提出了 3 个请求。需要 virtual 以允许 ORM 连接到属性并延迟加载它们,它会创建这些属性的动态代理。 - Chris Sainty” - 正如其他地方的问题所述。 link
  • 我还没有完全解决我遇到的问题,因为我不太明白发生了什么。我觉得我需要更多地研究 MVC 音乐商店教程(链接问题中引用的教程)所引用的 ORM。

标签: asp.net-mvc-3 entity-framework database-design virtual


【解决方案1】:

在这种特殊情况下,我没有使用引用另一个表的 Id 字段的传统方式。

我只需要更改以下内容:

公共 int 建立 ID { 获取;放; } 公共 int DrinkId { 获取;放; }

到以下:

public int EstablishmentsId { 获取;放; } 公共 int DrinksId { 获取;放; }

进行此更改后,我的表已按预期创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2023-03-24
    相关资源
    最近更新 更多