如何使用DB中的表控制器?

时间:2015-07-17 12:57:07

标签: c# asp.net asp.net-mvc database visual-studio-2012

在我的Licenses控制器中,我使用SQL脚本来创建表。有没有办法让该表使用我自己的控制器并查看模型?

这是我的许可控制器的一部分:

var list = GetAllCompanyNames();
foreach(var lists in list) {
    if (lists.Value == licenses.companyName) {
        string connectionString =
            "Data Source=(LocalDb)\\v11.0;AttachDbFilename=|DataDirectory|\\aspnet-LicenseManager-20141219012740.mdf;Initial Catalog=aspnet-LicenseManager-20141219012740;Integrated Security=True";
        using(SqlConnection con = new SqlConnection(connectionString)) {
            con.Open();
            using(SqlCommand com = new SqlCommand("CREATE TABLE " + "company_" + lists.Key + " (CompanyID INT, companyName TEXT)", con)) {
                com.ExecuteNonQuery();
            }
        }
    }
}

无法在互联网上找到任何解决方案。

1 个答案:

答案 0 :(得分:1)

您的控制器正在进行数据库访问。这不是控制人员的工作。通过将控制器与数据访问绑定,可以防止它们轻易分离。更好的方法是将数据库访问放在一个单独的库中,或者至少是一个单独的类。

您应该定义模型:

//All the properties of Product should be described here, Name, description, price etc
public class Product
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string Description {get; set;}
    public double Price {get; set;}
}

助手图书馆:

//This will contain handy functions for decreasing repetitive database code
public class MsSqlDatabaseHelpers
{
    public static DataTable GetDataTable(SqlCommand command, string connectionString)
    {
       DataTable dt = new DataTable();
       using (var connection = new SqlConnection(connectionString))
       {
           command.Connection = connection;
           connection.Open();
           dt.Load(command.ExecuteReader());
       }
       return dt;
    }
}

存储库(数据访问层):

//This will have methods for getting models from the database and also inserting and updating them (not shown)
public class MsSqlStoreRepository : IStoreRepository
{
    private string ConnectionString { get; set; }

    public MsSqlStoreRepository(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public List<Product> GetAllProducts()
    {
        var command = new SqlCommand("select id, name, description, price from products");
        var dt = MsSqlDatabaseHelpers.GetDataTable(command, ConnectionString);
        return dt.AsEnumerable().Select(r => GenerateProductFromDataRow(r)).ToList();
    }

    //I abstracted this logic out so we could reuse it elsewhere
    private Product GenerateProductFromDataRow(DataRow row)
    {
        return new Product()
        {
            Id = row.Field<int>("id"),
            Name = row.Field<string>("name"),
            Description = row.Field<string>("description"),
            Price = row.Field<double>("price")
        };
    }
}

那么你的控制器会是这样的:

public class ProductsController
{
    private IStoreRepository StoreRepository {get; set;}

    //When the controller is created, we'll initialize our data access layer
    public ProductsController()
    {
        StoreRepository = new MsSqlStoreRepository(Config.ConnectionString); //normally you'd use Dependency Injection instead of constructor
    }

    public ActionResult List()
    {
        var products = StoreRepository.GetAllProducts();
        return View(products);
    }
}

现在,您可以更方便地使用替代方案替换数据访问层 - 也许您还希望提供OracleStoreRepositoryXmlStoreRepository

请注意,数据库不知道站点或控制器。数据库层也是如此,它应该只知道数据库。