I am trying to use object initializer to set up a custom array in vb.net, there may be only 1 entry or there could be 100 on any given instance of this array. I have been successful in completing this task in C# however can not find documentation of completing it in Vb.net
I have a model:
Public Class Artist
Public Name As String
Public Task As String
End Class
within another model we have further listed this object as part of the collection
Public Property Artists() As Artist
which brings me to the controller
.Artists = New Artist() With
{.Name = "bob", .Task = "1"}
that is successful for 1 entry; how would I add another entry under the same instance of the object such as the following in c#
Artists = new Artist[]
{
new Artist() { name = "bob", Task = "1" },
new Artist() { name = "fred", Task = "2" },
new Artist() { name = "george", Task = "3" }
}
this all falls within a with statement itself being a sub of another object which seems to rule out traditional dimensioning
Dim cB = New CB {
.StoryTitle = "Test"
.IsbnNumber = 200
.Artists = new Artists...
}
Ultimate Solution
Dim cB = New CB With {
.StoryTitle = "Test",
.IsbnNumber = 200,
.Artists = New Artist() {New Artist() With {
.Name = "bob",
.Task = "1"
}, New Artist() With {
.Name = "fred",
.Task = "2"
}, New Artist() With {
.Name = "george",
.Task = "3"
}}
}
I have been successful in completing this task in C# however can not find documentation of completing it in Vb.net
Download ILSpy, drag/drop your Exe or Dll that you successfully created with C# and save project as a VB.Net project.
I'm bilingual with C# and VB.Net but when it comes to Lambda's and LINQ in VB.Net this is how I translate between the languages.
Or an even simpler and quicker method is: http://converter.telerik.com/
C#:
Artists a = new Artist[]
{
new Artist() { name = "bob", Task = "1" },
new Artist() { name = "fred", Task = "2" },
new Artist() { name = "george", Task = "3" }
}
VB.Net:
Dim a As Artists = New Artist() {New Artist() With {
.name = "bob",
.Task = "1"
}, New Artist() With {
.name = "fred",
.Task = "2"
}, New Artist() With {
.name = "george",
.Task = "3"
}}
Your syntax is a little bit off. Try this:
Dim artists() As Artist = {
New Artist() With {.Name = "bob", .Task = "1"},
New Artist() With {.Name = "bob", .Task = "1"}
}
Related
I'm trying to get a certain amount of animals that have the most comments once I try to delete one of them so I'm getting an error of:
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK__Comments__Animal__2EDAF651". The conflict occurred in database "PetShop", table "dbo.Comments", column 'AnimalId'. The statement has been terminated.
I want to make it possible that if I delete then you will move on to the next in line
My Controller for disply:
public async Task<IActionResult> Index()
{
var animal = _context.Animals.Include(c => c.Comments).OrderByDescending(c => c.Comments.Count).Take(2);
return View(await animal.ToListAsync());
}
My Controller for Delete:
public async Task<Animal> DeleteAnimal(int id)
{
var comment = await _context.Comments.FindAsync(id);
_context.Comments.Remove(comment!);
var animal = await _context.Animals.FindAsync(id);
_context.Animals.Remove(animal!);
await _context.SaveChangesAsync();
return animal!;
}
My Context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Comment>(entity =>
{
entity.HasOne(d => d.Animal)
.WithMany(p => p.Comments)
.HasForeignKey(d => d.AnimalId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK__Comments__Animal__2EDAF651");
});
modelBuilder.Entity<Category>(entity =>
entity.HasData(
new { CategoryId = 1, Name = "Dogs" },
new { CategoryId = 2, Name = "Cats" },
new { CategoryId = 3, Name = "Birds" },
new { CategoryId = 4, Name = "Rabbits" },
new { CategoryId = 5, Name = "Hamsters" }
)
);
modelBuilder.Entity<Animal>(entity =>
{
entity.HasData(
new { AnimalId = 1, Name = "Shoko", BirthDate = DateTime.Now.AddYears(-1).AddMonths(-1).AddDays(-12), Description = "Friendly and loyal", CategoryId = 1, PhotoUrl = "ShokoDog.jpg" },
new { AnimalId = 2, Name = "Bamba", BirthDate = DateTime.Now.AddYears(-2).AddMonths(-2).AddDays(-3), Description = "Furry and neutered", CategoryId = 2, PhotoUrl = "BambaCat.jpg" },
new { AnimalId = 3, Name = "Regev", BirthDate = DateTime.Now.AddYears(-1).AddMonths(-3).AddDays(-3), Description = "Speak", CategoryId = 3, PhotoUrl = "RegevBird.jpg" },
new { AnimalId = 4, Name = "Humi", BirthDate = DateTime.Now.AddYears(-3).AddMonths(-4).AddDays(-7), Description = "Cute and furry", CategoryId = 4, PhotoUrl = "HumiRabbit.jpg" },
new { AnimalId = 5, Name = "Tommy", BirthDate = DateTime.Now.AddYears(-1).AddMonths(-7).AddDays(-9), Description = "Love to play in the facilities", CategoryId = 5, PhotoUrl = "TommyHamster.jpg" });
});
OnModelCreatingPartial(modelBuilder);
}
You want to remove a parent Animal and related child Comments
To expand on Karlis' suggestions:
You have models and context as posted in the question (it's a bit problematic because you say to EF to set null, but the code and DB won't accept null) but you can do:
var a = context.Animals.Include(a => a.Comments).Find(id):
context.Comments.RemoveRange(a.Comments);
context.Animals.Remove(a);
context.SaveChanges();
This explicitly removes the comments then the animal
Change the context to use .OnDelete(DeleteBehavior.ClientCascade) then you can do:
var a = context.Animals.Include(a => a.Comments).Find(id):
context.Animals.Remove(a);
context.SaveChanges();
This causes EF to implicitly remove the comments it knows about when you tell it explicitly to remove the animal
Change the DB's foreign key to do an ON DELETE CASCADE, and change .OnDelete(DeleteBehavior.Cascade) then you can skip downloading the Comments (no include):
var a = context.Animals.Find(id):
context.Animals.Remove(a);
context.SaveChanges();
This causes the DB to remove the comments (EF doesn't know about them) when EF instructs to delete the animal
Broadly speaking, these are in order of "how bad of a mistake could you make" from "not very" to "quite a lot"
The error message reads that you are deleting Animal, which has comments associated. You should do one of the following:
Remove comments associated with a particular Animal before deleting the Animal.
Check EF configuration for cascade on delete
Alter FK to have cascade on delete (it depends on whether you are using a database-first or code-first approach)
I would go for the first approach because cascade on delete may be dangerous and silently remove unintentionally referenced data.
Hello All I added a Controller in my project like this:-
using Aero.Api.Models.ViewModels;
using Aero.Common.Interface;
using Aero.Data.Interface;
using Microsoft.Web.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Aero.Api.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/province")]
public class ProvinceController : BaseApiController
{
private IUserService _userService { get; set; }
// GET: States
public ProvinceController(IUserService userService, IMappingHelper mapper) :
base(mapper)
{
_userService = userService;
}
public List<StateProvinceModel> Get()
{
List<StateProvinceModel> states = new List<StateProvinceModel>();
StateProvinceModel stateProvince = new StateProvinceModel()
{
Id = "BC",
Value = "BC - British Columbia",
Name = "British Columbia",
Country = "Canada"
};
StateProvinceModel stateProvince1 = new StateProvinceModel()
{
Id = "QB",
Value = "QB- Quebec",
Name = "Quebec",
Country = "Canada"
};
StateProvinceModel stateProvince2 = new StateProvinceModel()
{
Id = "ON",
Value = "ON- Ontario",
Name = "Ontario",
Country = "Canada"
};
states.Add(stateProvince);
states.Add(stateProvince1);
states.Add(stateProvince2);
StateProvinceModel stateProvince3 = new StateProvinceModel()
{
Id = "IL",
Value = "IL - Illinois",
Name = "Illinois",
Country = "United States"
};
StateProvinceModel stateProvince4 = new StateProvinceModel()
{
Id = "GA",
Value = "GA-Georgia",
Name = "Georgia",
Country = "United States"
};
StateProvinceModel stateProvince5 = new StateProvinceModel()
{
Id = "NY",
Value = "NY- New York",
Name = "New York",
Country = "United States"
};
states.Add(stateProvince3);
states.Add(stateProvince4);
states.Add(stateProvince5);
return states;
}
}
}
when I try to call the Get method from browser like this:- http://localhost:44300/api/v1/province I get an error that the resource was not found. Other Urls on existing controllers work. For example a Url like this:- http://localhost:44300/api/v1/properties works perfectly fine.
Can anyone tell me what is going on ?
You should inherit your contoller class to ApiController instead of BaseApiContoller.
Ex: public class GoaAPIController : ApiController
Sir, You can Try changing The Method Name .
I have seeded the database using code first migration, however I noticed when I view the seeded data in index.html, the data is replicated.
This is the configuration file were I seeded the data:
internal sealed class Configuration : DbMigrationsConfiguration
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(OnlineBookStore.Models.OnlineBookStoreDB context)
{
var books = new System.Collections.Generic.List<Book>
{
new Book {
BookStatus = new BookStatus { Status = "New" },
Genre = new Genre { Name = "Thriller" },
Author = new Author { Name = "Paula Hawkins" },
Title = "The Girl On The Train",
Description = "Rachel catches the same commuter train morning. ",
ISBN = 0552779776,
},
new Book
{
BookStatus = new BookStatus { Status = "Best Seller" },
Genre = new Genre { Name = "Childrens" },
Author = new Author { Name = "Roald Dahl" },
Title = "The Witches",
Description = "Beware. Real witches dress in ordinary clothes",
ISBN = 0141365471,
},
},
};
books.ForEach(s =>context.Books.AddOrUpdate(p => new { p.ISBN, p.Title } ));
context.SaveChanges();
}
}
}
I am really unsure of were I am going wrong, spent days on this!
Really appreciate anyones help! thanks!
You need to specify the key in AddOrUpdate to prevent duplicates since Seed() runs with every update-database issued.
// build your books collection
var books = new []
{
new Book {
BookStatus = new BookStatus { Status = "New" },
Genre = new Genre { Name = "Thriller" },
Author = new Author { Name = "Paula Hawkins" },
Title = "The Girl On The Train",
Description = "Rachel catches the same commuter train morning. ",
ISBN = 0552779776,
},
new Book
{
BookStatus = new BookStatus { Status = "Best Seller" },
Genre = new Genre { Name = "Childrens" },
Author = new Author { Name = "Roald Dahl" },
Title = "The Witches",
Description = "Beware. Real witches dress in ordinary clothes",
ISBN = 0141365471,
},
},
};
context.Books.AddOrUpdate(p => new { p.ISBN, p.Title }, books);
context.SaveChanges();
See http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/
{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}
I've been following along with a tutorial by Julie Lerman about using EF CodeFirst to generate the database from code. I'm using MVC4 and working with the default controllers. All I want to do is generate the database. However, in her tutorial, she's working with a console application and calling a create_blog method in her Main function. The create_blog function does the work of creating the database as the name suggests.
In my Global.asax, I have this:
Database.SetInitializer(new CIT.Models.SampleData());
This is my SampleData class:
public class SampleData : CreateDatabaseIfNotExists<Context>
{
protected override void Seed(Context context)
{
base.Seed(context);
new List<Software> {
new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Adobe" }}},
new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "123463423453", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "81st Street" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Apple" }}},
new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "12346231434543", Platform = "PC", Notes = "Macs really rock!", PurchaseDate = "2011-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Microsoft" }}}
}.ForEach(s => context.Software.Add(s));
}
}
I get no errors when I compile. I just get no database. I looked in my App_Data and all that's there is the default database. I have a dbContext that is getting called because when I had errors in it, they pointed to that file. Do I need to have some kind of create method that is called when the site first compiles?
SetInitializer only sets the initializer strategy and the strategy is executed the first time you access the database. Try adding the following after calling SetInitializer
using (var context = new Context()) { context.Database.Initialize(true); }