0

I have a mvc 3 project and I need to populate sql database with data from xml file. So I added the console app project to the solution and wrote the code that will display all needed data on the screen. Now I want to write data into the database. Here is the chunk of code: (fom the console app)

    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);
        }
    }

First of all when I run the console app the NullReferenceException occures in MvcProjectName.Designer.cs file in the following line:

public WebStoreDataContext() : 
    base(global::System.Configuration.ConfigurationManager.ConnectionStrings["WebStoreConnectionString"].ConnectionString, mappingSource)                    

NullReferenceException: The reference to the object is not pointing to the object instance.

So, I have lots of questions:

1) How to integrate console app code with mvc 3 app code in one solution?

2) I've also found this post on stackoverflow. But can't I just add reference to MvcProject in references of ConsoleProject? And this way get access to the "mvc repositories" code?

3) Should I use ninject container in console app?

4) Is there any better implementation of loading data from xml file into slq database? I've never had two projects in one solution before, so mabby there are other ways to beautifully handle this situation?

Thanks for Your help in advance!

Edits:

I added app.config file with the connection string:

<add
    name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
     AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
  providerName="System.Data.SqlClient"
/>

Now when I run console app I get the following SqlException when the Linq to SQL ".submitChanges()" method is called:

An attempt to attach an auto-named database for file C:\Users\Aleksey\repos\working_copy\WebStore\LoadDataTool\bin\Debug\WebStore.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Also in the directory LoadDataTool\bin\Debug "WebStore" file with extension "Program Debug Database" appeared.

Community
  • 1
  • 1
Aleksei Chepovoi
  • 3,915
  • 8
  • 39
  • 77

2 Answers2

1

I guess that you need to define a connection string in the App.config file that is used by your console application (the same way you have it in your web.config):

<connectionStrings>
    <add 
        name="WebStoreConnectionString" 
        connectionString="YOUR CONNECTION STRING COMES HERE" 
        providerName="System.Data.SqlClient"
    />
</connectionStrings>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks! I added app.config with connection string to my DB. Get another exception. I should somehow to change this path: AttachDbFilename=|DataDirectory|\WebStore.mdf. What is the way to specify it implicitly? – Aleksei Chepovoi Jan 28 '13 at 15:21
  • Aleksei, on this topic, Take a look at this http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx. Also, this topic might help as well: http://stackoverflow.com/a/3501950/1220302 – anAgent Jan 28 '13 at 15:42
1

It's hard to make an accurate assumption on your solution architecture, but from what I'm reading, it doesn't sound like you've separated your Data Access Layer (DAL) from the presentation layer (MVC) - which seems to be why you're trying to referencing it in a console application.

With that assumption, here's how I would answer your questions.

  1. I wouldn't... But if I was going to I was 1) make sure that I have all the required references, 2) validate that the app.config file is setup correctly pointing to the correct database and server.
  2. I would separate your repositories in a different project and use a dependency resolver to inject them into your MVC Application. With that, the console application will only need to reference the DAL assembly - thus not needed all the references in your console app.
  3. If your think that you're going to be pulling out the DAL in the future, then yes. (**See #2 suggestion).
  4. Unless you can't run your solution without the XML file and database created, a better solution is to simply make an administration Controller and Action that allows you to upload your XML file and complete the tasks.

I hope that helps.

Update

For your issue

An attempt to attach an auto-named database for file

Change your connection string so that it looks something like;

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\WebStore.mdf;

A good source for connection strings is: http://www.connectionstrings.com/

anAgent
  • 2,550
  • 24
  • 34
  • I use pattern repository) And of course register dependencies in dependency resolver. Besides I don't have app.config in console app at all. This should be the problem – Aleksei Chepovoi Jan 28 '13 at 15:17
  • 1
    Hi Aleksei, I see that you're using the Repository Pattern. However, are your repositories defined in your MVC application? If so, I suggest that you move them out so you can reference your DAL in other assemblies. – anAgent Jan 28 '13 at 15:21
  • thanks! Now I get why the DAL should be defined in other project! I thought that for my not so big app this architecture would be enough. – Aleksei Chepovoi Jan 28 '13 at 15:23