2

単純なWCFアプリケーションに取り組んでいますが、リポジトリパターンを適切に設定するのに問題があります。アプリケーションの通信パターンは、おおよそここに示すとおりです。

私は言う部分に関心がありますAdmin Console Mode。このモードでは、管理者は、ユーザーの追加や既存のユーザーの表示など、いくつかの管理機能にアクセスできます。

このモードに必要なエンティティの1つの抽象コントラクトUsersは、次のとおりです。

public interface IUserRepository
{
    byte AddUser(string _loginname, string _loginpass);
    Users ShowAllUsers();
}

このリポジトリの具体的な実装:

public class UserRepository : IUserRepository
{
    public UserRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public byte AddUser(string _loginname, string _loginpass)
    {
        . . .
    }

    public Users ShowAllUsers()
    {
        string query = "select login_name,created_time from users";

        using(SqlConnection conn = new SqlConnection(_connectionString))
        {
            using(SqlCommand cmd = new SqlCommand(query, conn))
            {                    
                conn.Open();

                using(var reader = cmd.ExecuteReader())
                {
                    if(!reader.Read())
                        return null;

                    return new Users
                    {
                        Login_Name = reader.GetString(reader.GetOrdinal("login_name")),
                        Login_Pass = reader.GetString(reader.GetOrdinal("login_pass")),
                        Created_Time = reader.GetDateTime(reader.GetOrdinal("created_time")),
                    };
                }
            }
        }
    }
}

ホストレイヤーから、ShowAllUsersメソッドから返されたユーザーオブジェクトのリストにアクセスするにはどうすればよいですか?私はこの方法を試しました:

public void ShowUsers()
{
    Users user = _repo.ShowAllUsers();

    Console.WriteLine("Name\tCreated Time");

    foreach(Users u in user)
    {
        Console.WriteLine("{0}\t{1}",u.Login_Name,u.Created_Time);
    }
}

私が理解していることから、Usersオブジェクトは列挙可能なオブジェクトではないため、これは明らかに機能しません。オブジェクトが画面に表示されるように返されるように 、Usersエンティティとおよびrepository contractを変更するにはどうすればよいですか?repository implementationUsers

Users.cs
UserRepository.cs
IUserRepository.cs

4

1 に答える 1

4

実在物:

// note the singular form, it makes much more sense for me, as far as the object represents a single entity (user)
// also not an interface, optionally
public class User : IUser
{
}

リポジトリ:

public class UserRepository : IUserRepository
{
    public IEnumerable<IUser> ShowAllUsers()
    {
        ...
        while (reader.Read())
        {
             yield return new User
             {
                 ...
             };
        }
    }
}

ADO.NETクエリからORMに切り替える場合は、コードを書き直す必要がはるかに少ないため、どこでもインターフェイスを使用することをお勧めします。


使用法:

foreach (User u in users)
{
    Console.WriteLine("{0} created on {1}", u.Login, u.CreationTime);
}
于 2012-04-15T16:25:39.893 に答える