I have a created Entity Framework.I am trying to add a new songs and New album to the table. For example when I try to add a new song I used the method below and it tells me "Object reference not set to an instance of an object" on the s.Artist.ArtistName. I have a webform that shows a list of Artists in a drop down menu and now I want to add a new song for that artist. How do I do that?
public Song AddNewSongNav(String ArtistName, String SongName)
{
using (var context = new MyEntities())
{
var s = new Song();
s.SongTitle = SongName;
s.Artist.ArtistName = ArtistName;
s.Artist.WikipediaUrl="http://en.wikipedia.org/Testing";
context.Songs.AddObject(s);
context.SaveChanges();
return s;
}
}
The frame work for the Artist Table has ArtistID,ArtistName and WikiPediaURL. It has a navivgation property for Album and Song. It is linked to Song as 1 to many and Album as 1 to Many.
It has a Song table, which has a SongID, SongTitle and Artist_ArtistID. It has a navigation property of Artist and Album. It's linked as a many to many to the Albums table.
Finally the Album table has an AlbumID,AlbumTitle,CoverArt,Year,Genre,MimeType and Artist_ArtistID. It has a navigation property of Artist and Song.
The Artist property is not automatically created - you have to create an instance of the artist first:
var s = new Song();
s.SongTitle = SongName;
s.Artist = new Artist();
s.Artist.ArtistName = artistName;
Related
I have two tables. One is the product (the basic table) and the other table is a product class (which has specific properties for the product class). I am keeping the ID of the product (from the product table) inside the specific table. The problem comes when I try to use unit of work. I have to get the ID of the added item in the product (basic) table but since I haven't commited the transaction, the ID doesn't exist (since I am using auto increment in my database). When I wasn't using unit of work I had the advantage of objects in C#, that they are reference types and I could easy get out the ID from the newly added product item (product table) right after I had saved it to the table with (context.SaveChanges() method) but now.... Any ideas?
PS: MVC
Do something like bellow code:
db.MyJobContext.Add(job);
db.SaveChanges();
//get inserted Id
int JobId = job.Id;
var JobProvObj = new JobProvRel();
JobProvObj.JobId = JobId;
foreach (int P_id in Provinces)
{
JobProvObj.ProvinceId = P_id;
db.MyJobProvRelContext.Add(JobProvObj);
db.SaveChanges();
}
I'm using Entity Framework and I am trying to remove a NinjqEquiment from a list belonging to an instance of Ninja.When I retrieve the list of Ninjas,I make sure to include the equipment list, so I know they are there. Then I remove the equipment from the Ninja and try to save changes. I get the following error -
The entity type List`1 is not part of the model for the current
context.
using (var db = new NinjaDbContext())
{
//get ninjas with equipment included
var ninjas = GetAllNinjas();
//get ninja
var ninja = (from n in ninjas
where n.Id == id
select n).FirstOrDefault();
//get equipment
var eq = (from e in ninja.EquipmentOwned
where e.Id == removeEqId
select e).FirstOrDefault();
//remove eq from ninja
ninja.EquipmentOwned.Remove(eq);
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
//save ninja
db.SaveChanges();
}
Just remove this:
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
This causes the error.
EquipmentOwned is a List<Equipment>. It is not an Entry in EF terms so it is not tracked directly by it.
When you delete an entity from such collection, EF knows that there won't be any relationship between this particular ninja and this particular equipment. It won't delete equipment from database because other ninjas may use this equipment.
To delete it completely you should remove this equipment from corresponding DbSet<> like this:
using (var db = new NinjaContext())
{
//db.Equipment is a DbSet<Equipment>
//id is PrimaryKey of Equipment table
var eq = db.Equipment.Find(id);
db.Equipment.Remove(eq);
db.SaveChanges();
}
I'm new to asp .net web application.
Is it possible to retrieve data from Microsoft SQL Server and preview it in a menu drop down list where the data are already flter by alphabetical? For example when I click the menu "A", it will drop down menu and show the option I have for the menu "A".
Any one that done it before and can provide me the link to make it happen? If possible, the design is responsive design .
Thanks
I have a categories like This you can save them in database
enum MenuCategory { Cata = 1, Catb = 2 };
Add a menu control:
var menu1 = new Menu() { ID = "TestMenu" };
now we add first level of menu that is our category:
var cat = MenuCategory.Cata;
var menuItem = new MenuItem(cat.ToString(), cat.ToString());
menu1.Items.Add(menuItem);
now adding sublevel for this category. Get data from database by your method
var catItems = new DAL.Repositories.MenuRepository().GetAMenutblByCategory(Convert.ToInt16(cat));
now for each data that you retrieve from database add a menuitem:
foreach (var menutbl in catItems)
{
var childmenuItem = new MenuItem(menutbl.MenuValue, menutbl.MenuId.ToString(), "", menutbl.NavigationUrl);
menu1.FindItem(cat.ToString()).ChildItems.Add(childmenuItem);
}
You should do this for all of your category, And finally add your menu to page.
Panel1.Controls.Add(menu1);
if you are doing this on pageload please be sure checkin !ispostback
new MenuItem(strin text,string value, string imageurl,string navigationurl)
I am new to TreeView in asp.net so any help regarding populating nodes would be great.
I have a DataTable that gets populated by a SQLAdapter. It contains:
-House- -Region- -Division-
Aurora House Arizona Central
Copper Hills Arizona Central
Arbor House DFW Central
Angelina House Timberland West
I want to know how to place data or create a TreeView that would look similar to this:
Selection
Corporate
Division
Region
House(s)
I have spent a lot of time researching about how to do this and I just cant wrap my head around it I dont know if its my data that it is in DataTable that makes it harder to do.
This is all going to be based on if the user has access to that particular Corporate/Division/Region/House so it I would like to have TreeView for admin show everything but for others show only what they have access to.
I dont think that is going to be a problem as long as I get the SQL that populates the Data Table correct. My concern also is the duplicate Regions/Divisions how do I also have them only appear once and not multiple times?
Thank you for all your help.
Nick
Basically, you'd ideally like to have an object (well, collection) that mimics the hierarchy that you want to present with the treeview.
I'm assuming the list that comes from the database is as you presented it in your question, and I'm assuming that "Selection" column contains
Maybe you can use Linq to create such hierarchical collection. Or maybe you don't even need to create that collection - maybe you can just go ahead and start building the treeview as you iterate your data records using - for example - linq and some looping.
There may be some more elegant ways, but something like this should work:
var selections = dt.Select(r => Convert.ToString(r["Selection"])).Distinct().ToList();
foreach (string selection in selections)
{
// create treeview node here; add to treeview
object selectionNode = null; // change type to treeview node type
var corporateList = dt.Where(r => Convert.ToString(r["Selection"]) == selection).Select(r => Convert.ToString(r["Corporate"])).Distinct().ToList();
foreach (string corporate in corporateList)
{
// create treeview node here; add it as a child to selectionNode
object corporateNode = null; // change type to tv node
var divisions = dt.Where(r => Convert.ToString(r["Selection"]) == selection && Convert.ToString(r["Corporate"]) == corporate).Select(r => Convert.ToString(r["Division"])).Distinct().ToList();
foreach (string div in divisions)
{
// create treeview node here; add it as a child to corporateNode
}
}
}
You can dynamically create a TreeView Control like this:
using (var db = new FORMS())
{
//Get Chapters from selected form
var query = from b in db.CHAPTERS
select b;
//Create treeview hierarchy
foreach (var rootItem in query)
{
TreeNode myNode = new TreeNode(rootItem.titulo, rootItem.id.ToString());
var childQuery = from b in db.SECTIONS
where b.idChapter = rootItem.id
select b;
//Add childs
foreach (var childItem in childQuery)
{
TreeNode myChildNode = new TreeNode(childItem.titulo, childItem.id.ToString());
myNode.ChildNodes.Add(myChildNode);
}
ChapterTreeView.Nodes.Add(myNode);
}
}
In this case I only have two levels for my TreeView Control, but you can nest as many as you want.
i was looking at an example of how to do an insert in Linq to SQL and here it was it said:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.Add(new Product(..));
context.SubmitChanges();
but when i look at the below, (in my case the Table is UserInfo), the Table doesn't have an "Add" method:
public System.Data.Linq.Table<UserInfo> UserInfos
{
get
{
return this.GetTable<UserInfo>();
}
}
any clue what i am doing wrong here?
You should use the InsertOnSubmit method:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.InsertOnSubmit(new Product(..));
context.SubmitChanges();
The Add method exist on the EntitySet members, is mostly used when adding Child entities to a Parent one, for example:
var category = new Category{ Name = "Breveages"};
category.Products.Add(new Product{ Name = "Orange Juice"});
category.Products.Add(new Product{ Name = "Tomato Juice"});
category.Products.Add(new Product{ Name = "Cola"});
//...
context.Categories.InsertOnSubmit(category);
// This will insert the Category and
// the three Products we associated to.
EDIT: To do update operations, you just need to retrieve the entity by doing a query, or attaching it, for example:
var customer = context.Customers.Single( c => c.CustomerID == "ALFKI");
customer.ContactName = "New Contact Name";
context.SubmitChanges();
The DataContext tracks the changes of its related entities and when the SubmitChanges method is called, it will detect that change, and generate an Update SQL statement behind the scenes to do the update operation...