c# - ADO.NET MVC 查询外键

标签 c# mysql sql asp.net-mvc ado.net

我有两个用外键连接的模型,User 和 Farm。

我希望能够通过查询和类型选择一个用户:

@Model.Farm.FarmId

在我看来。这不会起作用,因为农场 Prop 为空。

Null

这是我的两个模型:

模型 1:

public class User
{
    [Key]
    public int UserId { get; set; }  

    public string UserName { get; set; }
    public string Password { get; set; }
    public string PasswordSalt { get; set; }
    public int Money { get; set; }

    public int FarmId { get; set; }

    [ForeignKey("FarmId")]
    public virtual Farm Farm { get; set; }
}

模型 2:

public class Farm
{
    public Farm()
    {
            User = new HashSet<User>();
    }

    [Key]
    public int FarmId { get; set; }

    public DateTime Created { get; set; }

    public int Age { get; set; }

    public virtual ICollection<User> User { get; set; }
}

获取用户查询:

public User GetUser(string userName)
{
    string sql = "SELECT * FROM Users WHERE UserName = @UserName";

    User user = null;

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        try
        {
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@userName", userName);

            connection.Open();

            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                user = new User
                {
                    UserId = (int)rdr["UserId"],
                    UserName = (string)rdr["UserName"],
                    Password = (string)rdr["Password"],
                    PasswordSalt = (string)rdr["PasswordSalt"],
                    Money = (int)rdr["Money"],
                    FarmId = (int)rdr["FarmId"],

                    Farm ??????
                };
            }

            if (rdr != null)
                rdr.Close();
        }
        catch
        {

        }
    }

    return user;
}

我的猜测是我必须进行某种连接,对吗?我仍然是一个查询新手,所以请耐心等待我:)

我不想使用 linq!

谢谢!

最佳答案

如果您想使用纯 SqlConnection,请完全放弃 Entity Framework。它不会帮助你。您添加到对象中的元数据将不再使用。

即使使用 Entity Framework,理论上您也可以使用 DbSet.SqlQuery或类似的方法来运行自定义 SQL 查询并取回事件对象。不过,我认为没有记录在案的方法来通过 JOIN 加载依赖项。您最终只会得到延迟加载支持,即在您枚举事物时在循环中选择查询。

如果您绝对必须使用复杂的手动方式而不是简单的 Linq 单行代码,那么您需要的是一个简单的 INNER JOIN (或者 LEFT JOIN 如果 Farm 是可选的)。这样,您也将从每一行的 Farm 表中获取所有字段。然后,您可以像处理其余字段一样,为每个用户手动实例化您的农场对象。

专业提示:

  1. 对阅读器使用 using() 以确保它正确关闭而不是您的 if
  2. 空的 catch { } 不会帮助您调试东西。
  3. 如果您只期望一个结果,为什么要使用 while 循环?

关于c# - ADO.NET MVC 查询外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574049/

相关文章:

c# - 如何使用 LINQ to XML 连接具有相同名称值的所有子元素

mysql - 为 postgres 创建 mysqldump

php - 如何获取多对多关系的不相关对象

sql - 将 rfc3339 字符串转换为带时区的时间戳

mysql - SQL 文本搜索 - EXACT 在空格之前,LIKE 在搜索词之后

C# 找出导致 Sql 异常的列

c# - 使用 C# 使用 Linq 更新 XML

c# - 在 C# 中使用 2D 图形的 Metro 应用程序

php - 拉拉维尔 6.2 : I get the same Id from different data in index() method

java - Java中基于用户输入的MySQL查询