【发布时间】:2013-01-28 14:09:07
【问题描述】:
我有一个 mvc 3 项目,我需要使用 xml 文件中的数据填充 sql 数据库。所以我将控制台应用程序项目添加到解决方案中,并编写了将在屏幕上显示所有需要的数据的代码。现在我想将数据写入数据库。这是代码块:(来自控制台应用程序)
public static void Main()
{
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<IItemsRepository>().To<ItemsRepository>();
ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
ninjectKernel.Bind<IShippingRepository>().To<ShippingRepository>();
var itemsRepository = ninjectKernel.Get<IItemsRepository>(); // redirection to datacontext file
var productRepository = ninjectKernel.Get<IProductRepository>();
var shippingRepository = ninjectKernel.Get<IShippingRepository>();
var doc = XDocument.Load(@"C:\div_kid.xml");
var offers = doc.Descendants("offer");
foreach (var offer in offers)
{ // here I use Linq to XML to get all needed data from xml file:
// name, description, price, category, shippingCost, shippingDetails
Product product = productRepository.CreateProduct(name, description, price, category, "Not Specified", "Not Specified");
Shipping shipping = shippingRepository.CreateShipping(shippingCost, shippingDetails);
// here I think I will just create "admin" user and assign its "UserId" to "userId"
Guid? userId = null;
Item item = itemsRepository.CreateItem(product.ProductId, shipping.ShippingId, (Guid) userId, DateTime.Now);
// Resharper highlights this line like unreachable. Why?
Console.WriteLine("name: {0}", offer.Element("name").Value);
}
}
首先,当我运行控制台应用程序时,NullReferenceException 发生在 MvcProjectName.Designer.cs 文件的以下行中:
public WebStoreDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["WebStoreConnectionString"].ConnectionString, mappingSource)
NullReferenceException:对对象的引用未指向对象实例。
所以,我有很多问题:
1) 如何将控制台应用代码与 mvc 3 应用代码集成到一个解决方案中?
2) 我还在 stackoverflow 上找到了this post。 但是我不能在 ConsoleProject 的引用中添加对 MvcProject 的引用吗?并且通过这种方式访问“mvc repositories”代码?
3) 我应该在控制台应用程序中使用 ninject 容器吗?
4) 将数据从 xml 文件加载到 slq 数据库中是否有更好的实现?我以前从来没有在一个解决方案中有两个项目,所以mabby还有其他方法可以很好地处理这种情况吗?
提前感谢您的帮助!
编辑:
我添加了带有连接字符串的 app.config 文件:
<add
name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient"
/>
现在,当我运行控制台应用程序时,当调用 Linq to SQL“.submitChanges()”方法时,我得到以下 SqlException:
尝试为文件 C:\Users\Aleksey\repos\working_copy\WebStore\LoadDataTool\bin\Debug\WebStore.mdf 附加自动命名数据库失败。存在同名数据库,或指定文件无法打开,或位于 UNC 共享上。
在 LoadDataTool\bin\Debug 目录中也出现了扩展名为“Program Debug Database”的“WebStore”文件。
【问题讨论】:
-
我更新了答案,希望能解决您的连接字符串错误。
标签: asp.net asp.net-mvc asp.net-mvc-3 architecture